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

feat: frontend_snippet > hubspot oauth flow #74

Merged
merged 3 commits into from
Nov 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/api/.env.example
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
ENV=dev
PROD_DISTRIBUTION=managed # could be self-host if you want to run it locally
DISTRIBUTION=managed # could be self-host if you want to run it locally
DATABASE_URL=
JWT_SECRET="SECRET"
POSTGRES_HOST=
Expand Down
1 change: 1 addition & 0 deletions packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"passport-jwt": "^4.0.1",
"passport-local": "^1.0.0",
"pino-pretty": "^10.2.3",
"qs": "^6.11.2",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
"uuid": "^9.0.1"
Expand Down
53 changes: 53 additions & 0 deletions packages/api/src/@core/connections/connections.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { Controller, Get, Query, Res } from '@nestjs/common';
import { Response } from 'express'; // Importing the Express Response type for type checking
import { CrmConnectionsService } from './crm/services/crm-connection.service';
import { ProviderVertical, getProviderVertical } from '../utils/providers';
import { LoggerService } from '../logger/logger.service';

Check warning on line 5 in packages/api/src/@core/connections/connections.controller.ts

View workflow job for this annotation

GitHub Actions / build-api (16.x)

'LoggerService' is defined but never used

@Controller('connections')
export class ConnectionsController {
constructor(private readonly crmConnectionsService: CrmConnectionsService) {}
@Get('oauth/callback')
handleCallback(
@Res() res: Response,
@Query('state') state: string,
@Query('code') code: string,
@Query('accountURL') zohoAccountURL?: string,
) {
try {
if (!state || !code) throw new Error('no params found');
const stateData = JSON.parse(decodeURIComponent(state));
const { projectId, linkedUserId, providerName, returnUrl } = stateData;
//TODO; ADD VERIFICATION OF PARAMS
switch (getProviderVertical(providerName)) {
case ProviderVertical.CRM:
const zohoAccount = zohoAccountURL ? zohoAccountURL : '';
this.crmConnectionsService.handleCRMCallBack(
projectId,
linkedUserId,
providerName,
code,
zohoAccount,
);
case ProviderVertical.ATS:
break;
case ProviderVertical.Accounting:
break;
case ProviderVertical.FileStorage:
break;
case ProviderVertical.HRIS:
break;
case ProviderVertical.MarketingAutomation:
break;
case ProviderVertical.Ticketing:
break;
case ProviderVertical.Unknown:
break;
}

res.redirect(returnUrl);
} catch (error) {
console.error('An error occurred', error.response?.data || error.message);
}
}
}
3 changes: 3 additions & 0 deletions packages/api/src/@core/connections/connections.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { Module } from '@nestjs/common';
import { CrmConnectionModule } from './crm/crm-connection.module';
import { ConnectionsController } from './connections.controller';
import { LoggerService } from '../logger/logger.service';

Check warning on line 4 in packages/api/src/@core/connections/connections.module.ts

View workflow job for this annotation

GitHub Actions / build-api (16.x)

'LoggerService' is defined but never used

@Module({
controllers: [ConnectionsController],
imports: [CrmConnectionModule],
})
export class ConnectionsModule {}

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Module } from '@nestjs/common';
import { CrmConnectionsController } from './crm-connection.controller';
import { CrmConnectionsService } from './services/crm-connection.service';
import { PrismaService } from 'src/@core/prisma/prisma.service';
import { FreshsalesConnectionService } from './services/freshsales/freshsales.service';
Expand All @@ -10,7 +9,6 @@ import { ZohoConnectionService } from './services/zoho/zoho.service';
import { LoggerService } from 'src/@core/logger/logger.service';

@Module({
controllers: [CrmConnectionsController],
providers: [
CrmConnectionsService,
PrismaService,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,82 @@
import { Prisma } from '@prisma/client';
import { HubspotOAuthResponse } from '../../types';
import { LoggerService } from 'src/@core/logger/logger.service';
import qs from 'qs';

Check warning on line 8 in packages/api/src/@core/connections/crm/services/hubspot/hubspot.service.ts

View workflow job for this annotation

GitHub Actions / build-api (16.x)

'qs' is defined but never used

@Injectable()
export class HubspotConnectionService {
constructor(private prisma: PrismaService, private logger: LoggerService) {
this.logger.setContext(HubspotConnectionService.name);
}
async addLinkedUserAndProjectTest() {
// Adding a new organization
const newOrganization = {
name: 'New Organization',
stripe_customer_id: 'stripe-customer-123',
};

const org = await this.prisma.organizations.create({
data: newOrganization,
});
this.logger.log('Added new organisation ' + org);

// Example data for a new project
const newProject = {
name: 'New Project',
id_organization: 1n, // bigint value
};
const data1 = await this.prisma.projects.create({
data: newProject,
});
this.logger.log('Added new project ' + data1);

const newLinkedUser = {
linked_user_origin_id: '12345',
alias: 'ACME COMPANY',
status: 'Active',
id_project: 1n, // bigint value
};
const data = await this.prisma.linked_users.create({
data: newLinkedUser,
});
this.logger.log('Added new linked_user ' + data);
}

async handleHubspotCallback(
linkedUserId: string,
projectId: string,
code: string,
) {
try {
//first create a linked_user
//TMP STEP = first create a linked_user and a project id
//await this.addLinkedUserAndProjectTest();
const newLinkedUser = {
linked_user_origin_id: '12345',
alias: 'ACME COMPANY',
status: 'Active',
id_project: 1n, // bigint value
};
const data_ = await this.prisma.linked_users.create({
data: newLinkedUser,
});
this.logger.log('Added new linked_user ' + data_);
//reconstruct the redirect URI that was passed in the frontend it must be the same
const REDIRECT_URI = `${config.OAUTH_REDIRECT_BASE}/oauth/crm/callback`; //tocheck

const formData = {
const REDIRECT_URI = `${config.OAUTH_REDIRECT_BASE}/connections/oauth/callback`; //tocheck
const formData = new URLSearchParams({
grant_type: 'authorization_code',
client_id: config.HUBSPOT_CLIENT_ID,
client_secret: config.HUBSPOT_CLIENT_SECRET,
redirect_uri: REDIRECT_URI,
code: code,
};
});
const res = await axios.post(
'https://api.hubapi.com/oauth/v1/token',
formData,
formData.toString(),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
},
},
);
const data: HubspotOAuthResponse = res.data;
//console.log('OAuth credentials : hubspot ', data);
Expand All @@ -58,6 +107,7 @@
// without it, we cant retrieve the right row in our db
},
});
this.logger.log('Successfully added tokens inside DB ' + db_res);
} catch (error) {
if (axios.isAxiosError(error)) {
// Handle Axios-specific errors
Expand All @@ -68,7 +118,10 @@
//console.error('Error with Prisma request:', error);
this.logger.error('Error with Prisma request:', error.message);
}
this.logger.error('An error occurred', error);
this.logger.error(
'An error occurred...',
error.response?.data || error.message,
);
}
}
async handleHubspotTokenRefresh(connectionId: bigint, refresh_token: string) {
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/@core/sentry/sentry.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export class SentryModule {
static forRoot(): DynamicModule {
const isProduction = config.NODE_ENV === 'production';
const sentry_dsn = config.SENTRY_DSN;
const distribution = config.PROD_DISTRIBUTION;
const distribution = config.DISTRIBUTION;

//enable sentry only if we are in production environment and if the product is managed by Panora
if (isProduction && sentry_dsn && distribution == 'managed') {
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/@core/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const config = {
OAUTH_REDIRECT_BASE: process.env.OAUTH_REDIRECT_BASE,
SENTRY_DSN: process.env.SENTRY_DSN,
NODE_ENV: process.env.ENV,
PROD_DISTRIBUTION: process.env.PROD_DISTRIBUTION,
DISTRIBUTION: process.env.DISTRIBUTION,
};

export default config;
48 changes: 48 additions & 0 deletions packages/api/src/@core/utils/providers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export const CRM_PROVIDERS = [
'zoho',
'zendesk',
'hubspot',
'pipedrive',
'freshsales',
];
export const HRIS_PROVIDERS = [];
export const ATS_PROVIDERS = [];
export const ACCOUNTING_PROVIDERS = [];
export const TICKETING_PROVIDERS = [];
export const MARKETING_AUTOMATION_PROVIDERS = [];
export const FILE_STORAGE_PROVIDERS = [];

export enum ProviderVertical {
CRM = 'CRM',
HRIS = 'HRIS',
ATS = 'ATS',
Accounting = 'Accounting',
Ticketing = 'Ticketing',
MarketingAutomation = 'Marketing Automation',
FileStorage = 'File Storage',
Unknown = 'Unknown', // Used if the provider does not match any category
}
export function getProviderVertical(providerName: string): ProviderVertical {
if (CRM_PROVIDERS.includes(providerName)) {
return ProviderVertical.CRM;
}
if (HRIS_PROVIDERS.includes(providerName)) {
return ProviderVertical.HRIS;
}
if (ATS_PROVIDERS.includes(providerName)) {
return ProviderVertical.ATS;
}
if (ACCOUNTING_PROVIDERS.includes(providerName)) {
return ProviderVertical.Accounting;
}
if (TICKETING_PROVIDERS.includes(providerName)) {
return ProviderVertical.Ticketing;
}
if (MARKETING_AUTOMATION_PROVIDERS.includes(providerName)) {
return ProviderVertical.MarketingAutomation;
}
if (FILE_STORAGE_PROVIDERS.includes(providerName)) {
return ProviderVertical.FileStorage;
}
return ProviderVertical.Unknown;
}
1 change: 1 addition & 0 deletions packages/api/src/app.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Injectable } from '@nestjs/common';
import { LoggerService } from './@core/logger/logger.service';

@Injectable()
export class AppService {
Expand Down
1 change: 1 addition & 0 deletions packages/frontend-snippet/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CLIENT_ID= #hubspot client id
18 changes: 18 additions & 0 deletions packages/frontend-snippet/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module.exports = {
root: true,
env: { browser: true, es2020: true },
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:react-hooks/recommended',
],
ignorePatterns: ['dist', '.eslintrc.cjs'],
parser: '@typescript-eslint/parser',
plugins: ['react-refresh'],
rules: {
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
}
26 changes: 26 additions & 0 deletions packages/frontend-snippet/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

.env
27 changes: 27 additions & 0 deletions packages/frontend-snippet/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# React + TypeScript + Vite

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.

Currently, two official plugins are available:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

## Expanding the ESLint configuration

If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:

- Configure the top-level `parserOptions` property like this:

```js
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname,
},
```

- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list
13 changes: 13 additions & 0 deletions packages/frontend-snippet/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
Loading
Loading