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

fix: #448 #481

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

fix: #448 #481

wants to merge 2 commits into from

Conversation

developerdhruv
Copy link

@developerdhruv developerdhruv commented Jun 5, 2024

fix issue: #448
/claim #448

Summary by CodeRabbit

  • New Features

    • Introduced AffinityConnectionService to manage OAuth callbacks and token refresh for the Affinity CRM service.
    • Added AffinityService to handle adding and syncing contacts with Affinity.
    • Implemented AffinityMapper to convert data between unified contact and Affinity contact formats.
  • Dependencies

    • Added @nestjs/axios, axios, and nestjs to the project dependencies.

Copy link

changeset-bot bot commented Jun 5, 2024

⚠️ No Changeset found

Latest commit: 92502b4

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 Jun 5, 2024

@developerdhruv 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

CLAassistant commented Jun 5, 2024

CLA assistant check
All committers have signed the CLA.

Copy link

algora-pbc bot commented Jun 5, 2024

💵 To receive payouts, sign up on Algora, link your Github account and connect with Stripe/Alipay.

Copy link
Contributor

coderabbitai bot commented Jun 5, 2024

Walkthrough

The recent updates focus on integrating the Affinity CRM service into the existing system. Key changes include adding dependencies for NestJS and Axios, introducing new services for handling OAuth and contact synchronization with Affinity, and refining the structure and imports across various modules to support these functionalities.

Changes

File/Path Change Summary
package.json Added dependencies: @nestjs/axios, axios, and nestjs.
.../crm.connection.module.ts Imported HttpModule and AffinityConnectionService, modified imports and providers arrays.
.../crm/services/affinity/affinityCrm.service.ts Introduced AffinityConnectionService to handle OAuth callbacks and token refresh for Affinity CRM.
.../crm/contact/contact.module.ts Imported and added AffinityService to the imports section.
.../crm/contact/services/affinity/index.ts Added AffinityService class to handle adding and syncing contacts with Affinity CRM.
.../crm/contact/services/affinity/mappers.ts Introduced AffinityMapper class for converting data between unified and Affinity contact formats.
.../crm/contact/services/affinity/types.ts Added interfaces: AffinityContact, AffinityContactInput, and AffinityContactOutput.
.../crm/contact/services/attio/index.ts Reorganized imports and added methods for contact management in AffinityService.
.../crm/contact/services/contact.service.ts Added two blank lines after import statements.
.../crm/contact/types/mappingsTypes.ts Imported AffinityMapper and updated contactUnificationMapping with affinity property.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant CRMSystem
    participant AffinityConnectionService
    participant AffinityService
    participant HttpService

    User->>CRMSystem: Initiates OAuth Callback
    CRMSystem->>AffinityConnectionService: handleCallback()
    AffinityConnectionService->>HttpService: POST OAuth token request
    HttpService-->>AffinityConnectionService: Response with tokens
    AffinityConnectionService-->>CRMSystem: Return Connection

    User->>CRMSystem: Add Contact
    CRMSystem->>AffinityService: addContact()
    AffinityService->>HttpService: POST contact data
    HttpService-->>AffinityService: Response with contact ID
    AffinityService-->>CRMSystem: Return Contact ID
Loading

Poem

In the world of code, a change so grand,
Affinity CRM now at hand.
With NestJS and Axios, we connect,
OAuth flows, contacts to collect.
A rabbit's joy in every line,
For seamless sync, it's truly fine.
🐰✨


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.
    • @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 as 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.

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

socket-security bot commented Jun 5, 2024

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/@nestjs/[email protected] None 0 19.1 kB nestjscore
npm/[email protected] None 0 1.02 kB quangv
npm/[email protected] None 0 241 kB rbuckton
npm/[email protected] environment Transitive: eval, filesystem, shell +20 54.1 MB lovell

🚮 Removed packages: npm/[email protected], npm/[email protected]

View full report↗︎

Copy link

socket-security bot commented Jun 5, 2024

🚨 Potential security issues detected. Learn more about Socket for GitHub ↗︎

To accept the risk, merge this PR and you will not be notified again.

Alert Package NoteSource
Install scripts npm/[email protected]
  • Install script: install
  • Source: node install/check
Install scripts npm/[email protected]
  • Install script: install
  • Source: node install/check

View full report↗︎

Next steps

What is an install script?

Install scripts are run when the package is installed. The majority of malware in npm is hidden in install scripts.

Packages should not be running non-essential scripts during install and there are often solutions to problems people solve with install scripts that can be run at publish time instead.

Take a deeper look at the dependency

Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support [AT] socket [DOT] dev.

Remove the package

If you happen to install a dependency that Socket reports as Known Malware you should immediately remove it and select a different dependency. For other alert types, you may may wish to investigate alternative packages or consider if there are other ways to mitigate the specific risk posed by the dependency.

Mark a package as acceptable risk

To ignore an alert, reply with a comment starting with @SocketSecurity ignore followed by a space separated list of ecosystem/package-name@version specifiers. e.g. @SocketSecurity ignore npm/[email protected] or ignore all packages with @SocketSecurity ignore-all

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

Outside diff range and nitpick comments (3)
packages/api/src/crm/contact/services/contact.service.ts (3)

Line range hint 179-180: Refactor to use optional chaining for better readability and safety.

- existingContact && existingContact.crm_email_addresses[index]
+ existingContact?.crm_email_addresses[index]

Also applies to: 203-203, 227-227


Line range hint 444-446: Replace forEach with for...of for better performance and readability.

- values.forEach((value) => {
+ for (const value of values) {

Also applies to: 530-532


Line range hint 603-605: This code is unreachable. Please review the logic to ensure that all code paths are necessary and reachable.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 04ce302 and 1385134.

Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
Files selected for processing (10)
  • package.json (1 hunks)
  • packages/api/src/@core/connections/crm/crm.connection.module.ts (3 hunks)
  • packages/api/src/@core/connections/crm/services/affinity/affinityCrm.service.ts (1 hunks)
  • packages/api/src/crm/contact/contact.module.ts (2 hunks)
  • packages/api/src/crm/contact/services/affinity/index.ts (1 hunks)
  • packages/api/src/crm/contact/services/affinity/mappers.ts (1 hunks)
  • packages/api/src/crm/contact/services/affinity/types.ts (1 hunks)
  • packages/api/src/crm/contact/services/attio/index.ts (1 hunks)
  • packages/api/src/crm/contact/services/contact.service.ts (1 hunks)
  • packages/api/src/crm/contact/types/mappingsTypes.ts (2 hunks)
Files skipped from review due to trivial changes (1)
  • packages/api/src/crm/contact/services/affinity/types.ts
Additional context used
Biome
packages/api/src/crm/contact/services/contact.service.ts

[error] 179-180: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 203-203: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 227-227: Change to an optional chain. (lint/complexity/useOptionalChain)

Unsafe fix: Change to an optional chain.


[error] 444-446: Prefer for...of instead of forEach. (lint/complexity/noForEach)

forEach may lead to performance issues when working with large arrays. When combined with functions like filter or map, this causes multiple iterations over the same type.


[error] 530-532: Prefer for...of instead of forEach. (lint/complexity/noForEach)

forEach may lead to performance issues when working with large arrays. When combined with functions like filter or map, this causes multiple iterations over the same type.


[error] 603-605: This code is unreachable (lint/correctness/noUnreachable)

Additional comments not posted (11)
package.json (2)

32-32: Dependency @nestjs/axios added correctly.


33-33: Dependency axios added correctly.

packages/api/src/crm/contact/services/affinity/mappers.ts (1)

10-47: The implementation of AffinityMapper looks correct and adheres to the IContactMapper interface requirements.

packages/api/src/crm/contact/types/mappingsTypes.ts (1)

Line range hint 6-39: Integration of AffinityMapper into contactUnificationMapping is done correctly, ensuring proper method binding and context management.

packages/api/src/crm/contact/contact.module.ts (1)

Line range hint 17-45: AffinityService correctly added to the providers of ContactModule. This aligns with NestJS best practices for module configuration.

packages/api/src/@core/connections/crm/crm.connection.module.ts (2)

Line range hint 2-20: HttpModule correctly added to the imports of CrmConnectionModule. This is essential for enabling HTTP communication capabilities within the module.


Line range hint 3-36: AffinityConnectionService correctly added to the providers of CrmConnectionModule. This setup is crucial for managing CRM connections.

packages/api/src/crm/contact/services/affinity/index.ts (1)

13-118: The implementation of AffinityService is robust, featuring comprehensive error handling, logging, and proper use of HTTP services for contact management. This aligns well with the objectives of enhancing CRM functionalities.

packages/api/src/@core/connections/crm/services/affinity/affinityCrm.service.ts (2)

26-38: Constructor properly initializes the service with necessary dependencies and registers the service. Good use of dependency injection for maintainability and testability.


40-72: Ensure proper error handling in handleCallback method.

Verification successful

The search results indicate that there are numerous instances of try blocks across the codebase, suggesting that error handling is a common practice. However, to ensure proper error handling in the handleCallback method, we need to verify if the error handling in this specific method is consistent with the patterns used in other parts of the codebase.

Given the extensive list of files containing try blocks, it would be more efficient to focus on a few representative examples to compare their error handling practices with the handleCallback method.


The extracted error handling patterns from the representative files show that they generally follow a consistent approach of logging the error and sometimes using a custom error handling function. Here are the key observations:

  1. Logging the Error: Most methods log the error using a logger instance.
  2. Custom Error Handling: Some methods use a custom error handling function like handleServiceError.

The handleCallback method in affinityCrm.service.ts already logs the error using this.logger.error and throws a new error with a specific message. This approach is consistent with the patterns observed in other parts of the codebase.

Observations:

  • Logging: The handleCallback method logs the error, which is a common practice in the codebase.
  • Error Throwing: The method throws a new error with a specific message, which is also a reasonable approach.

Conclusion:

The error handling in the handleCallback method is consistent with the practices observed in other parts of the codebase.

Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify proper error handling in `handleCallback` method.
# Test: Search for error handling patterns in similar methods across the codebase.
rg --type python "try {"

Length of output: 100



Script:

#!/bin/bash
# Description: Verify proper error handling in `handleCallback` method.
# Test: Search for error handling patterns in similar methods across the codebase.
rg --type ts "try {"

Length of output: 96



Script:

#!/bin/bash
# Description: Verify proper error handling in `handleCallback` method.
# Test: Search for error handling patterns in similar methods across the codebase.
rg --type ts "try \{"

Length of output: 36320



Script:

#!/bin/bash
# Description: Extract error handling patterns from a few representative files for comparison.
# Extracting error handling from user.controller.ts
rg --context 5 "try \{" packages/api/src/ticketing/user/user.controller.ts

# Extracting error handling from sync.service.ts
rg --context 5 "try \{" packages/api/src/ticketing/user/sync/sync.service.ts

# Extracting error handling from user.service.ts
rg --context 5 "try \{" packages/api/src/ticketing/user/services/user.service.ts

Length of output: 3158

packages/api/src/crm/contact/services/attio/index.ts (1)

9-21: Constructor sets up the service context and registers the service correctly. Good use of dependency injection.

Comment on lines 75 to 103
async handleTokenRefresh(opts: RefreshParams): Promise<any> {
const { connectionId, refreshToken } = opts;
const clientId = this.env.get('AFFINITY_CLIENT_ID');
const clientSecret = this.env.get('AFFINITY_CLIENT_SECRET');

try {
const tokenResponse = await lastValueFrom(this.httpService.post('https://api.affinity.co/oauth/token', {
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
client_secret: clientSecret,
}));

const { access_token, refresh_token, expires_in } = tokenResponse.data;

await this.prisma.connection.update({
where: { id: connectionId },
data: {
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: new Date(Date.now() + expires_in * 1000),
},
});

return { access_token, refresh_token, expires_in };
} catch (error) {
this.logger.error('Error refreshing token for Affinity', error);
throw new Error('Failed to refresh token for Affinity');
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The handleTokenRefresh method follows a similar pattern to handleCallback and properly uses async-await with try-catch for error handling. Consider adding more specific error messages to enhance debugging and user feedback.

- throw new Error('Failed to refresh token for Affinity');
+ throw new Error(`Failed to refresh token for Affinity: ${error.message}`);
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
async handleTokenRefresh(opts: RefreshParams): Promise<any> {
const { connectionId, refreshToken } = opts;
const clientId = this.env.get('AFFINITY_CLIENT_ID');
const clientSecret = this.env.get('AFFINITY_CLIENT_SECRET');
try {
const tokenResponse = await lastValueFrom(this.httpService.post('https://api.affinity.co/oauth/token', {
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
client_secret: clientSecret,
}));
const { access_token, refresh_token, expires_in } = tokenResponse.data;
await this.prisma.connection.update({
where: { id: connectionId },
data: {
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: new Date(Date.now() + expires_in * 1000),
},
});
return { access_token, refresh_token, expires_in };
} catch (error) {
this.logger.error('Error refreshing token for Affinity', error);
throw new Error('Failed to refresh token for Affinity');
}
async handleTokenRefresh(opts: RefreshParams): Promise<any> {
const { connectionId, refreshToken } = opts;
const clientId = this.env.get('AFFINITY_CLIENT_ID');
const clientSecret = this.env.get('AFFINITY_CLIENT_SECRET');
try {
const tokenResponse = await lastValueFrom(this.httpService.post('https://api.affinity.co/oauth/token', {
grant_type: 'refresh_token',
refresh_token: refreshToken,
client_id: clientId,
client_secret: clientSecret,
}));
const { access_token, refresh_token, expires_in } = tokenResponse.data;
await this.prisma.connection.update({
where: { id: connectionId },
data: {
accessToken: access_token,
refreshToken: refresh_token,
expiresAt: new Date(Date.now() + expires_in * 1000),
},
});
return { access_token, refresh_token, expires_in };
} catch (error) {
this.logger.error('Error refreshing token for Affinity', error);
throw new Error(`Failed to refresh token for Affinity: ${error.message}`);
}

"gitmoji-cli": "^9.0.0",
"nestjs": "^0.0.1",
Copy link
Contributor

Choose a reason for hiding this comment

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

Check the version of nestjs. The version ^0.0.1 seems incorrect, possibly a typo or a placeholder.

Comment on lines +23 to +30
async addContact(
contactData: AffinityContactInput,
linkedUserId: string,
): Promise<ApiResponse<AffinityContactOutput>> {
// Implementation for adding a contact to Affinity CRM
// This should interact with Affinity CRM's API to add a contact
return;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The addContact method lacks implementation details. Ensure that the method interacts with the Affinity CRM's API as intended.

Please implement the interaction with Affinity CRM's API or provide a stub if this is a work in progress.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

  • Added support for Affinity CRM, including OAuth callbacks and token refresh.
  • Introduced AffinityService for adding and syncing contacts.
  • Added AffinityMapper for converting data between unified contact and Affinity contact formats.
  • Updated dependencies: added @nestjs/axios, axios, and nestjs.
  • Enhanced contact management with new methods for handling Affinity contacts.

@@ -15,7 +17,7 @@ import { AttioConnectionService } from './services/attio/attio.service';
import { ConnectionsStrategiesService } from '@@core/connections-strategies/connections-strategies.service';

Copy link

Choose a reason for hiding this comment

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

Consider removing the trailing comma after HttpModule for consistency.

@@ -0,0 +1,119 @@
import { Injectable } from '@nestjs/common';
Copy link

Choose a reason for hiding this comment

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

Consider adding a newline at the end of the file for POSIX compliance.

try {
const accessToken = await this.getAccessToken(linkedUserId);
const response = await lastValueFrom(
this.httpService.post('https://api.affinity.co/contacts', contactData, {
Copy link

Choose a reason for hiding this comment

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

Use handleServiceError to manage errors consistently across services.

): Promise<ApiResponse<AffinityContactOutput[]>> {
try {
const accessToken = await this.getAccessToken(linkedUserId);
const response = await lastValueFrom(
Copy link

Choose a reason for hiding this comment

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

Use handleServiceError to manage errors consistently across services.

@@ -0,0 +1,48 @@
import { Address } from '@crm/@lib/@types';
Copy link

Choose a reason for hiding this comment

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

Consider adding a newline at the end of the file.

Comment on lines +21 to +35
lastName: source.lastName,
email: source.email,
phone: source.phone,
company: source.company,
};
}

unify(
source: AffinityContactOutput | AffinityContactOutput[],
customFieldMappings?: {
slug: string;
remote_id: string;
}[],
): UnifiedContactOutput | UnifiedContactOutput[] {
if (Array.isArray(source)) {
Copy link

Choose a reason for hiding this comment

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

Handle potential null or undefined values in source properties.


export type AffinityContactInput = Partial<AffinityContact>;
export type AffinityContactOutput = AffinityContact;

Copy link

Choose a reason for hiding this comment

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

Add a newline at the end of the file.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1385134 and 92502b4.

Files selected for processing (1)
  • packages/api/src/@core/connections/crm/services/affinity/affinityCrm.service.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/api/src/@core/connections/crm/services/affinity/affinityCrm.service.ts

@developerdhruv
Copy link
Author

@rflihxyz
Please share when this PR will get reviewed.

@naelob
Copy link
Contributor

naelob commented Jun 6, 2024

@rflihxyz Please share when this PR will get reviewed.

Hey @developerdhruv ! Can you upload a loom video of you testing the integration end-to-end ?
In the meantime I'll review it !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants