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/passthrough #125

Merged
merged 6 commits into from
Dec 6, 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
3 changes: 3 additions & 0 deletions apps/frontend-snippet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,12 @@
"ci": "pnpm run lint && pnpm run build"
},
"dependencies": {
"@tanstack/react-query": "^5.12.2",
"api": "workspace:*",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-loader-spinner": "^5.4.5",
"shared-types": "workspace:*",
"tailwind-scrollbar-hide": "^1.1.7",
"uuid": "^9.0.1"
},
Expand Down
6 changes: 6 additions & 0 deletions apps/frontend-snippet/src/helpers/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const config = {
API_URL: import.meta.env.VITE_BACKEND_DOMAIN,
};

export default config;

16 changes: 0 additions & 16 deletions apps/frontend-snippet/src/helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,3 @@
export enum CRM_PROVIDERS {
ZOHO = 'zoho',
ZENDESK = 'zendesk',
HUBSPOT = 'hubspot',
PIPEDRIVE = 'pipedrive',
FRESHSALES = 'freshsales',
}

export enum ACCOUNTING_PROVIDERS {
PENNYLANE = 'pennylane',
FRESHBOOKS = 'freshbooks',
CLEARBOOKS = 'clearbooks',
FREEAGENT = 'freeagent',
SAGE = 'sage',
}

type ProviderConfig = {
clientId: string;
scopes: string;
Expand Down
17 changes: 17 additions & 0 deletions apps/frontend-snippet/src/hooks/queries/useLinkedUser.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useQuery } from '@tanstack/react-query';
import { linked_users as LinkedUser } from 'api';
import config from '@/helpers/config';

const useLinkedUser = (id: string) => {
return useQuery({
queryKey: ['linked-users', id],
queryFn: async (): Promise<LinkedUser> => {
const response = await fetch(`${config.API_URL}/linked-users?id=${id}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
}
});
};
export default useLinkedUser;
17 changes: 17 additions & 0 deletions apps/frontend-snippet/src/hooks/queries/useUniqueMagicLink.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { useQuery } from '@tanstack/react-query';
import { invite_links as MagicLink } from 'api';
import config from '@/helpers/config';

const useUniqueMagicLink = (id: string) => {
return useQuery({
queryKey: ['magic-link', id],
queryFn: async (): Promise<MagicLink> => {
const response = await fetch(`${config.API_URL}/magic-link?id=${id}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
}
});
};
export default useUniqueMagicLink;
17 changes: 9 additions & 8 deletions apps/frontend-snippet/src/hooks/useOAuth.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { useState, useEffect } from 'react';
import { findProviderVertical, providersConfig } from '../helpers/utils';
import { findProviderVertical, providersConfig } from '@/helpers/utils';
import config from '@/helpers/config';

type UseOAuthProps = {
clientId?: string;
providerName: string; // Name of the OAuth provider
returnUrl: string; // Return URL after OAuth flow
projectId: string; // Project ID
linkedUserId: string; // Linked User ID
projectId: string | undefined; // Project ID
linkedUserId: string | undefined; // Linked User ID
onSuccess: () => void;
};

Expand All @@ -20,22 +21,22 @@ const useOAuth = ({ providerName, returnUrl, projectId, linkedUserId, onSuccess
}, []);

const constructAuthUrl = () => {
const encodedRedirectUrl = encodeURIComponent(`${import.meta.env.VITE_BACKEND_DOMAIN}/connections/oauth/callback`);
const encodedRedirectUrl = encodeURIComponent(`${config.API_URL}/connections/oauth/callback`);
const state = encodeURIComponent(JSON.stringify({ projectId, linkedUserId, providerName, returnUrl }));

const vertical = findProviderVertical(providerName);
if(vertical == null) {
return null;
}

const config = providersConfig[vertical][providerName];
if (!config) {
const config_ = providersConfig[vertical][providerName];
if (!config_) {
throw new Error(`Unsupported provider: ${providerName}`);
}

const { clientId, scopes } = config;
const { clientId, scopes } = config_;

const baseUrl = config.authBaseUrl;
const baseUrl = config_.authBaseUrl;
if (!baseUrl) {
throw new Error(`Unsupported provider: ${providerName}`);
}
Expand Down
40 changes: 20 additions & 20 deletions apps/frontend-snippet/src/lib/ProviderModal.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { useEffect, useState } from 'react';
import { TailSpin } from 'react-loader-spinner'
import useOAuth from '../hooks/useOAuth';
import { findProviderByName, providersArray } from '../helpers/utils';

const categories = ['CRM', 'Ticketing', 'Marketing Automation','ATS', 'Accounting', 'File Storage', 'HR & Payroll'];

import useOAuth from '@/hooks/useOAuth';
import { findProviderByName, providersArray } from '@/helpers/utils';
import {categoriesVerticals} from 'shared-types';
import useLinkedUser from '@/hooks/queries/useLinkedUser';
import useUniqueMagicLink from '@/hooks/queries/useUniqueMagicLink';

const LoadingOverlay = ({ providerName }: { providerName: string }) => {
const provider = findProviderByName(providerName);
Expand Down Expand Up @@ -35,37 +35,37 @@ const LoadingOverlay = ({ providerName }: { providerName: string }) => {
};

const ProviderModal = () => {
const [selectedCategory, setSelectedCategory] = useState(categories[0]); // Default to the first category
const [selectedCategory, setSelectedCategory] = useState(categoriesVerticals[0] as string); // Default to the first category
const [selectedProvider, setSelectedProvider] = useState('');
const [loading, setLoading] = useState<{
status: boolean; provider: string
}>({status: false, provider: ''});
const [linkedUserId, setLinkedUserId] = useState('');
const [projectId, setProjectId] = useState('');
const [uniqueMagicLinkId, setUniqueMagicLinkId] = useState('');

useEffect(() => {
useEffect(() => {
const queryParams = new URLSearchParams(window.location.search);
const uniqueId = queryParams.get('unique-id');
const uniqueId = queryParams.get('uniqueLink');
if (uniqueId) {
setLinkedUserId(uniqueId);
}
const projectId = queryParams.get('project-id');
if (projectId) {
setProjectId(projectId);
setUniqueMagicLinkId(uniqueId);
}
}, []);

//console.log("user-id "+ linkedUserId);
//console.log("project-id "+ projectId);

const {data: magicLink} = useUniqueMagicLink(uniqueMagicLinkId);
const {data: linkedUser} = useLinkedUser(magicLink?.id_linked_user as string);

//TODO: externalize that in the backend => from
const { open, isReady } = useOAuth({
providerName: selectedProvider, // This will be set when a provider is clicked
returnUrl: 'http://127.0.0.1:5174/', // Replace with the actual return URL
projectId: projectId, // Replace with the actual project ID
linkedUserId: linkedUserId, //TODO: uuidv4(), // Replace with the actual user ID
projectId: linkedUser?.id_project, // Replace with the actual project ID
linkedUserId: linkedUser?.id_linked_user, //TODO: uuidv4(), // Replace with the actual user ID
onSuccess: () => console.log('OAuth successful'),
});




const onWindowClose = () => {
setSelectedProvider('');
setLoading({
Expand Down Expand Up @@ -104,7 +104,7 @@ const ProviderModal = () => {
{!loading.status ?
<div className="p-4 max-h-[32rem] overflow-auto scrollbar-hide">
<div className="flex mb-4 outline-none flex-wrap">
{categories.map((category, index) => (
{categoriesVerticals.map((category, index) => (
<button
key={index}
className={`px-3 py-1 mb-2 mr-1 rounded-full text-xs font-medium transition duration-150 ${selectedCategory === category ? 'bg-indigo-600 hover:bg-indigo-500 ' : 'bg-neutral-700 hover:bg-neutral-600'}`}
Expand Down
6 changes: 5 additions & 1 deletion apps/frontend-snippet/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,

"paths": {
"@/*": [
"./src/*"
],
},
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
Expand Down
6 changes: 6 additions & 0 deletions apps/frontend-snippet/vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'

// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src')
}
}
})
3 changes: 2 additions & 1 deletion apps/webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
"tailwindcss-animate": "^1.0.7",
"zod": "^3.22.4",
"zustand": "^4.4.7",
"api": "workspace:*"
"api": "workspace:*",
"shared-types": "workspace:*"
},
"devDependencies": {
"@types/node": "^20.3.1",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ import useDefineFieldMutation from "@/hooks/mutations/useDefineFieldMutation"
import useMapFieldMutation from "@/hooks/mutations/useMapFieldMutation"
import { useEffect, useState } from "react"
import useFieldMappings from "@/hooks/useFieldMappings"
import useSourceCustomFields from "@/hooks/useSourceCustomFields"
import { useStandardObjects } from "@/hooks/useStandardObjects"
import useProviderProperties from "@/hooks/useProviderProperties"

export function FModal({ onClose }: {onClose: () => void}) {
const [standardModel, setStandardModel] = useState('');
Expand All @@ -48,7 +48,8 @@ export function FModal({ onClose }: {onClose: () => void}) {
const { data: mappings } = useFieldMappings();
const { mutate: mutateDefineField } = useDefineFieldMutation();
const { mutate: mutateMapField } = useMapFieldMutation();
const { data: sourceCustomFields, error, isLoading } = useSourceCustomFields(sourceProvider);
const { data: sourceCustomFields, error, isLoading } = useProviderProperties(linkedUserId,sourceProvider,standardModel);

const { data: sObjects } = useStandardObjects();

useEffect(() => {
Expand Down
18 changes: 18 additions & 0 deletions apps/webapp/src/hooks/useProviderProperties.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import config from '@/utils/config';
import { useQuery } from '@tanstack/react-query';
import { getProviderVertical } from 'shared-types';

const useProviderProperties = (linkedUserId: string, providerId: string, standardObject: string) => {
return useQuery({
queryKey: ['providerProperties', linkedUserId, providerId, standardObject],
// eslint-disable-next-line @typescript-eslint/no-explicit-any
queryFn: async (): Promise<Record<string, any>[]> => {
const response = await fetch(`${config.API_URL}/${getProviderVertical(providerId).toLowerCase()}/${standardObject.toLowerCase()}/properties?linkedUserId=${linkedUserId}&providerId=${providerId}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
}
});
};
export default useProviderProperties;
20 changes: 0 additions & 20 deletions apps/webapp/src/hooks/useSourceCustomFields.tsx

This file was deleted.

1 change: 0 additions & 1 deletion packages/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
export * from '@prisma/client';
//export * from './src/@core/utils/types';
3 changes: 2 additions & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"pino-pretty": "^10.2.3",
"reflect-metadata": "^0.1.13",
"rxjs": "^7.8.1",
"uuid": "^9.0.1"
"uuid": "^9.0.1",
"shared-types": "workspace:*"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
Expand Down
3 changes: 1 addition & 2 deletions packages/api/src/@core/connections/connections.controller.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import { Controller, Get, Query, Res } from '@nestjs/common';
import { Response } from 'express';
import { CrmConnectionsService } from './crm/services/crm-connection.service';
import { ProviderVertical, getProviderVertical } from '@@core/utils/providers';
import { LoggerService } from '@@core/logger/logger.service';
import { handleServiceError } from '@@core/utils/errors';
import { PrismaService } from '@@core/prisma/prisma.service';

import { ProviderVertical, getProviderVertical } from 'shared-types';
@Controller('connections')
export class ConnectionsController {
constructor(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,5 +58,4 @@ export class FieldMappingController {
mapFieldToProvider(@Body() mapFieldToProviderDto: MapFieldToProviderDto) {
return this.fieldMappingService.mapFieldToProvider(mapFieldToProviderDto);
}
//TODO: /origin-custom-fields?provider=${provider}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Body, Controller, Get, Post } from '@nestjs/common';
import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { LinkedUsersService } from './linked-users.service';
import { LoggerService } from '../logger/logger.service';
import { CreateLinkedUserDto } from './dto/create-linked-user.dto';
Expand All @@ -20,4 +20,8 @@ export class LinkedUsersController {
getLinkedUsers() {
return this.linkedUsersService.getLinkedUsers();
}
@Get()
getLinkedUser(@Query('id') id: string) {
return this.linkedUsersService.getLinkedUser(id);
}
}
7 changes: 7 additions & 0 deletions packages/api/src/@core/linked-users/linked-users.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ export class LinkedUsersService {
async getLinkedUsers() {
return await this.prisma.linked_users.findMany();
}
async getLinkedUser(id: string) {
return await this.prisma.linked_users.findFirst({
where: {
id_linked_user: id,
},
});
}
async addLinkedUser(data: CreateLinkedUserDto) {
const { id_project, ...rest } = data;
const res = await this.prisma.linked_users.create({
Expand Down
12 changes: 11 additions & 1 deletion packages/api/src/@core/magic-link/magic-link.controller.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { LoggerService } from '@@core/logger/logger.service';
import { Body, Controller, Post } from '@nestjs/common';
import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { MagicLinkService } from './magic-link.service';
import { CreateMagicLinkDto } from './dto/create-magic-link.dto';

Expand All @@ -16,4 +16,14 @@ export class MagicLinkController {
createLink(@Body() data: CreateMagicLinkDto) {
return this.magicLinkService.createUniqueLink(data);
}

@Get()
getMagicLinks() {
return this.magicLinkService.getMagicLinks();
}

@Get()
getMagicLink(@Query('id') id: string) {
return this.magicLinkService.getMagicLink(id);
}
}
12 changes: 12 additions & 0 deletions packages/api/src/@core/magic-link/magic-link.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ export class MagicLinkService {
this.logger.setContext(MagicLinkService.name);
}

async getMagicLinks() {
return await this.prisma.invite_links.findMany();
}

async getMagicLink(id: string) {
return await this.prisma.invite_links.findFirst({
where: {
id_invite_link: id,
},
});
}

async createUniqueLink(data: CreateMagicLinkDto) {
const checkDup = await this.prisma.linked_users.findFirst({
where: {
Expand Down
Loading
Loading