diff --git a/packages/api/scripts/init.sql b/packages/api/scripts/init.sql index 4bdb1db6e..53d1eabcd 100644 --- a/packages/api/scripts/init.sql +++ b/packages/api/scripts/init.sql @@ -19,6 +19,14 @@ CREATE TABLE webhooks_payloads CONSTRAINT PK_webhooks_payload PRIMARY KEY ( id_webhooks_payload ) ); +-- ************************************** rate_limit_state +CREATE TABLE rate_limit_state ( + id_rate_limit_state uuid NOT NULL, + id_connection NOT NULL, + last_request_timestamp TIMESTAMP NOT NULL, + request_count INTEGER NOT NULL + CONSTRAINT PK_rate_limit_state PRIMARY KEY ( id_rate_limit_state ) +); -- ************************************** webhook_endpoints CREATE TABLE webhook_endpoints diff --git a/packages/api/src/@core/@core-services/queues/queue.module.ts b/packages/api/src/@core/@core-services/queues/queue.module.ts index 8ce85065e..937d48fa3 100644 --- a/packages/api/src/@core/@core-services/queues/queue.module.ts +++ b/packages/api/src/@core/@core-services/queues/queue.module.ts @@ -21,6 +21,9 @@ import { Queues } from './types'; { name: Queues.RAG_DOCUMENT_PROCESSING, }, + { + name: Queues.RATE_LIMIT_FAILED_JOBS, + }, ), ], providers: [BullQueueService], diff --git a/packages/api/src/@core/@core-services/queues/shared.service.ts b/packages/api/src/@core/@core-services/queues/shared.service.ts index b059e2529..782392705 100644 --- a/packages/api/src/@core/@core-services/queues/shared.service.ts +++ b/packages/api/src/@core/@core-services/queues/shared.service.ts @@ -16,6 +16,8 @@ export class BullQueueService { public readonly failedPassthroughRequestsQueue: Queue, @InjectQueue(Queues.RAG_DOCUMENT_PROCESSING) private ragDocumentQueue: Queue, + @InjectQueue(Queues.RATE_LIMIT_FAILED_JOBS) + private rlFailedJobsQueue: Queue, ) {} // getters @@ -35,6 +37,9 @@ export class BullQueueService { getRagDocumentQueue() { return this.ragDocumentQueue; } + getRlFailedJobsQueue() { + return this.rlFailedJobsQueue; + } async removeRepeatableJob(jobName: string) { const jobs = await this.syncJobsQueue.getRepeatableJobs(); diff --git a/packages/api/src/@core/@core-services/queues/types.ts b/packages/api/src/@core/@core-services/queues/types.ts index 5cd578e4b..4f690cc6d 100644 --- a/packages/api/src/@core/@core-services/queues/types.ts +++ b/packages/api/src/@core/@core-services/queues/types.ts @@ -4,4 +4,5 @@ export enum Queues { SYNC_JOBS_WORKER = 'SYNC_JOBS_WORKER', // Queue which syncs data from remote 3rd parties FAILED_PASSTHROUGH_REQUESTS_HANDLER = 'FAILED_PASSTHROUGH_REQUESTS_HANDLER', // Queue which handles failed passthrough request due to rate limit and retries it with backOff RAG_DOCUMENT_PROCESSING = 'RAG_DOCUMENT_PROCESSING', + RATE_LIMIT_FAILED_JOBS = 'RATE_LIMIT_FAILED_JOBS', } diff --git a/packages/api/src/@core/@core-services/unification/ingest-data.service.ts b/packages/api/src/@core/@core-services/unification/ingest-data.service.ts index 74f11f6b0..0c051996a 100644 --- a/packages/api/src/@core/@core-services/unification/ingest-data.service.ts +++ b/packages/api/src/@core/@core-services/unification/ingest-data.service.ts @@ -1,22 +1,24 @@ -import { Injectable } from '@nestjs/common'; -import { CoreSyncRegistry } from '../registries/core-sync.registry'; -import { CoreUnification } from './core-unification.service'; -import { v4 as uuidv4 } from 'uuid'; -import { PrismaService } from '../prisma/prisma.service'; +import { ConnectionUtils } from '@@core/connections/@utils'; +import { FieldMappingService } from '@@core/field-mapping/field-mapping.service'; +import { RagService } from '@@core/rag/rag.service'; +import { FileInfo } from '@@core/rag/types'; +import { RateLimitError } from '@@core/rate-limit/error'; import { ApiResponse, getFileExtensionFromMimeType, TargetObject, } from '@@core/utils/types'; -import { UnifySourceType } from '@@core/utils/types/unify.output'; -import { WebhookService } from '../webhooks/panora-webhooks/webhook.service'; -import { ConnectionUtils } from '@@core/connections/@utils'; import { IBaseObjectService, SyncParam } from '@@core/utils/types/interface'; -import { FieldMappingService } from '@@core/field-mapping/field-mapping.service'; -import { LoggerService } from '../logger/logger.service'; -import { RagService } from '@@core/rag/rag.service'; -import { FileInfo } from '@@core/rag/types'; +import { UnifySourceType } from '@@core/utils/types/unify.output'; +import { Injectable } from '@nestjs/common'; import { fs_files as FileStorageFile } from '@prisma/client'; +import { v4 as uuidv4 } from 'uuid'; +import { LoggerService } from '../logger/logger.service'; +import { PrismaService } from '../prisma/prisma.service'; +import { BullQueueService } from '../queues/shared.service'; +import { CoreSyncRegistry } from '../registries/core-sync.registry'; +import { WebhookService } from '../webhooks/panora-webhooks/webhook.service'; +import { CoreUnification } from './core-unification.service'; @Injectable() export class IngestDataService { @@ -29,6 +31,7 @@ export class IngestDataService { private logger: LoggerService, private fieldMappingService: FieldMappingService, private ragService: RagService, + private queues: BullQueueService, ) {} async syncForLinkedUser( @@ -87,7 +90,7 @@ export class IngestDataService { // Construct the syncParam object dynamically const syncParam: SyncParam = { - linkedUserId, + connection, custom_properties: remoteProperties, }; @@ -144,6 +147,32 @@ export class IngestDataService { `Error syncing ${integrationId} ${commonObject}: ${syncError.message}`, syncError, ); + // handle the case where ratelimit is throwed + if (syncError instanceof RateLimitError) { + this.logger.warn( + `Rate limit exceeded for ${integrationId} ${commonObject}. Retry after ${syncError.retryAfter}ms.`, + ); + // You might want to add some logic here to handle the rate limit, + // such as scheduling a retry or notifying the user. + const rlFailedJobsQueue = this.queues.getRlFailedJobsQueue(); + await rlFailedJobsQueue.add( + 'rate-limit-sync', + { + method: 'syncForLinkedUser', + args: [ + integrationId, + linkedUserId, + vertical, + commonObject, + service, + params, + wh_real_time_trigger, + ], + }, + { delay: syncError.retryAfter }, + ); + return; + } // Optionally, you could create an event to log this error /*await this.prisma.events.create({ data: { diff --git a/packages/api/src/@core/core.module.ts b/packages/api/src/@core/core.module.ts index bb7310259..23db40aaf 100644 --- a/packages/api/src/@core/core.module.ts +++ b/packages/api/src/@core/core.module.ts @@ -15,8 +15,9 @@ import { OrganisationsModule } from './organisations/organisations.module'; import { PassthroughModule } from './passthrough/passthrough.module'; import { ProjectConnectorsModule } from './project-connectors/project-connectors.module'; import { ProjectsModule } from './projects/projects.module'; -import { SyncModule } from './sync/sync.module'; import { RagModule } from './rag/rag.module'; +import { RateLimitModule } from './rate-limit/rate-limit.module'; +import { SyncModule } from './sync/sync.module'; @Module({ imports: [ @@ -36,6 +37,7 @@ import { RagModule } from './rag/rag.module'; SyncModule, ProjectConnectorsModule, BullQueueModule, + RateLimitModule, RagModule, ], exports: [ @@ -55,6 +57,7 @@ import { RagModule } from './rag/rag.module'; SyncModule, ProjectConnectorsModule, IngestDataService, + RateLimitModule, BullQueueModule, RagModule, ], diff --git a/packages/api/src/@core/rate-limit/error.ts b/packages/api/src/@core/rate-limit/error.ts new file mode 100644 index 000000000..5d16f2997 --- /dev/null +++ b/packages/api/src/@core/rate-limit/error.ts @@ -0,0 +1,6 @@ +export class RateLimitError extends Error { + constructor(message: string, public retryAfter: number) { + super(message); + this.name = 'RateLimitError'; + } +} diff --git a/packages/api/src/@core/rate-limit/rate-limit.consumer.ts b/packages/api/src/@core/rate-limit/rate-limit.consumer.ts new file mode 100644 index 000000000..251f4220c --- /dev/null +++ b/packages/api/src/@core/rate-limit/rate-limit.consumer.ts @@ -0,0 +1,33 @@ +import { Queues } from '@@core/@core-services/queues/types'; +import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; +import { Process, Processor } from '@nestjs/bull'; +import { Job } from 'bull'; + +@Processor(Queues.RATE_LIMIT_FAILED_JOBS) +export class RateLimitJobProcessor { + constructor(private ingestDataService: IngestDataService) {} + + @Process('rate-limit-sync') + async processRateLimitedJob(job: Job<{ method: string; args: any[] }>) { + const { method, args } = job.data; + try { + if (method === 'syncForLinkedUser') { + await this.ingestDataService.syncForLinkedUser( + ...(args as Parameters< + typeof this.ingestDataService.syncForLinkedUser + >), + ); + } + + // Fallback for other methods (if any) + /*const targetInstance = this.moduleRef.get(target, { strict: false }); + if (targetInstance && typeof targetInstance[method] === 'function') { + await targetInstance[method](...args); + return; + }*/ + } catch (error) { + console.error(`Error processing rate-limited job: ${error.message}`); + throw error; + } + } +} diff --git a/packages/api/src/@core/rate-limit/rate-limit.decorator.ts b/packages/api/src/@core/rate-limit/rate-limit.decorator.ts new file mode 100644 index 000000000..a0d2a5e80 --- /dev/null +++ b/packages/api/src/@core/rate-limit/rate-limit.decorator.ts @@ -0,0 +1,33 @@ +import { RateLimitService } from './rate-limit.service'; + +export function RateLimit() { + return function ( + target: any, + propertyKey: string, + descriptor: PropertyDescriptor, + ) { + const originalMethod = descriptor.value; + + descriptor.value = async function (...args: any[]) { + const rateLimitService: RateLimitService = (this as any).rateLimitService; + const { connection } = args[0]; + + if (!rateLimitService) { + console.error('RateLimitService not found in the class instance'); + return originalMethod.apply(this, args); + } + + try { + await rateLimitService.checkRateLimit( + connection.id_connection, + connection.provider_slug, + ); + return await originalMethod.apply(this, args); + } catch (error) { + throw error; + } + }; + + return descriptor; + }; +} diff --git a/packages/api/src/@core/rate-limit/rate-limit.module.ts b/packages/api/src/@core/rate-limit/rate-limit.module.ts new file mode 100644 index 000000000..3051c47ec --- /dev/null +++ b/packages/api/src/@core/rate-limit/rate-limit.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { RateLimitJobProcessor } from './rate-limit.consumer'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; +import { WebhookService } from '@@core/@core-services/webhooks/panora-webhooks/webhook.service'; + +@Module({ + providers: [RateLimitJobProcessor, WebhookService, PrismaService], +}) +export class RateLimitModule {} diff --git a/packages/api/src/@core/rate-limit/rate-limit.service.ts b/packages/api/src/@core/rate-limit/rate-limit.service.ts new file mode 100644 index 000000000..18b36e60d --- /dev/null +++ b/packages/api/src/@core/rate-limit/rate-limit.service.ts @@ -0,0 +1,137 @@ +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; +import { Injectable } from '@nestjs/common'; +import { RateLimitError } from './error'; + +interface RateLimitPolicy { + timeWindow: number; + maxRequests: number; +} + +@Injectable() +export class RateLimitService { + constructor(private prisma: PrismaService) {} + + async checkRateLimit( + connectionId: string, + providerSlug: string, + ): Promise { + const policies = await this.getRateLimitPolicies(providerSlug); + + for (const policy of policies) { + const { timeWindow, maxRequests } = policy; + const windowStart = new Date(Date.now() - timeWindow * 1000); + + const requestCount = await this.prisma.events.count({ + where: { + id_connection: connectionId, + timestamp: { gte: windowStart }, + type: { endsWith: '.pulled' }, + }, + }); + + if (requestCount >= maxRequests) { + const retryAfter = await this.getRetryAfter(connectionId); + throw new RateLimitError('Rate limit exceeded', retryAfter); + } + } + + return true; // All checks passed + } + + private async getRateLimitPolicies( + providerSlug: string, + ): Promise { + const policies: Record = { + hubspot: [ + { timeWindow: 10, maxRequests: 110 }, // 110 calls per 10 seconds + { timeWindow: 86400, maxRequests: 250000 }, // 250k calls per day + ], + }; + return policies[providerSlug] || []; + } + + async getRetryAfter(connectionId: string): Promise { + const connection = await this.prisma.connections.findUnique({ + where: { id_connection: connectionId }, + }); + + if (!connection) { + throw new Error(`Connection not found for id: ${connectionId}`); + } + + const policies = await this.getRateLimitPolicies(connection.provider_slug); + + if (policies.length === 0) { + return 10000; // 10 seconds default delay if no policies + } + + let maxTimeUntilReset = 0; + + for (const policy of policies) { + const windowStart = new Date(Date.now() - policy.timeWindow * 1000); + const requestCount = await this.prisma.events.count({ + where: { + id_connection: connectionId, + timestamp: { gte: windowStart }, + type: { endsWith: '.pulled' }, + }, + }); + + if (requestCount >= policy.maxRequests) { + const latestEvent = await this.prisma.events.findFirst({ + where: { + id_connection: connectionId, + type: { endsWith: '.pulled' }, + }, + orderBy: { timestamp: 'desc' }, + }); + + if (latestEvent) { + const timeSinceLastRequest = + Date.now() - latestEvent.timestamp.getTime(); + const timeUntilReset = + policy.timeWindow * 1000 - timeSinceLastRequest; + maxTimeUntilReset = Math.max(maxTimeUntilReset, timeUntilReset); + } + } + } + + if (maxTimeUntilReset <= 0) { + return 0; + } + + const buffer = 1000; // 1 second buffer + return maxTimeUntilReset + buffer; + } + + /*async retryWithBackoff(config: any): Promise { + return backOff( + async () => { + try { + const response = await axios(config); + return response; + } catch (error) { + if (error.response && error.response.status === 429) { + const retryAfter = await this.getRetryAfter(config.connectionId); + if (retryAfter) { + await new Promise((resolve) => setTimeout(resolve, retryAfter)); + } + throw error; // Rethrow to trigger backoff + } + throw error; // Rethrow non-rate-limit errors + } + }, + { + numOfAttempts: 10, + startingDelay: 1000, + timeMultiple: 2, + maxDelay: 60000, + jitter: 'full', + retry: (e: Error, attemptNumber: number) => { + console.log(`Retry attempt ${attemptNumber} due to: ${e.message}`); + return true; + }, + }, + ); + }*/ +} diff --git a/packages/api/src/@core/utils/decorators/utils.ts b/packages/api/src/@core/utils/decorators/utils.ts deleted file mode 100644 index 3f0fc49e3..000000000 --- a/packages/api/src/@core/utils/decorators/utils.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { - CRM_PROVIDERS, - HRIS_PROVIDERS, - ATS_PROVIDERS, - ACCOUNTING_PROVIDERS, - TICKETING_PROVIDERS, - MARKETINGAUTOMATION_PROVIDERS, - FILESTORAGE_PROVIDERS, - ECOMMERCE_PROVIDERS, - EcommerceObject, - CrmObject, - FileStorageObject, - TicketingObject, - HrisObject, - AccountingObject, - MarketingAutomationObject, - AtsObject, -} from '@panora/shared'; -import * as fs from 'fs'; -import * as path from 'path'; - -interface ProviderMetadata { - actions: string[]; - supportedFields: string[][]; -} - -export async function generatePanoraParamsSpec(spec: any) { - const verticals = { - crm: [CRM_PROVIDERS, CrmObject], - hris: [HRIS_PROVIDERS, HrisObject], - ats: [ATS_PROVIDERS, AtsObject], - accounting: [ACCOUNTING_PROVIDERS, AccountingObject], - ticketing: [TICKETING_PROVIDERS, TicketingObject], - marketingautomation: [ - MARKETINGAUTOMATION_PROVIDERS, - MarketingAutomationObject, - ], - filestorage: [FILESTORAGE_PROVIDERS, FileStorageObject], - ecommerce: [ECOMMERCE_PROVIDERS, EcommerceObject], - }; - - for (const [vertical, [providers, COMMON_OBJECTS]] of Object.entries( - verticals, - )) { - for (const objectKey of Object.values(COMMON_OBJECTS)) { - for (const provider of providers as string[]) { - try { - const metadataPath = path.join( - process.cwd(), - 'src', - vertical.toLowerCase(), - objectKey as string, - 'services', - provider, - 'metadata.json', - ); - - const metadataRaw = fs.readFileSync(metadataPath, 'utf8'); - const metadata: ProviderMetadata = JSON.parse(metadataRaw); - - if (metadata) { - metadata.actions.forEach((action, index) => { - const path = `/${vertical.toLowerCase()}/${objectKey}s`; - const op = - action === 'list' ? 'get' : action === 'create' ? 'post' : ''; - - if (spec.paths[path] && spec.paths[path][op]) { - if (!spec.paths[path][op]['x-panora-remote-platforms']) { - spec.paths[path][op]['x-panora-remote-platforms'] = {}; - } - // Ensure the provider array is initialized - if ( - !spec.paths[path][op]['x-panora-remote-platforms'][provider] - ) { - spec.paths[path][op]['x-panora-remote-platforms'][provider] = - []; // Initialize as an array - } - for (const field of metadata.supportedFields[index]) { - spec.paths[path][op]['x-panora-remote-platforms'][ - provider - ].push(field); - } - } else { - console.warn( - `Path or operation not found in spec: ${path} ${op}`, - ); - } - }); - } - } catch (error) { - console.error(error); - } - } - } - } - - return spec; -} diff --git a/packages/api/src/@core/utils/types/interface.ts b/packages/api/src/@core/utils/types/interface.ts index e744718c0..e6b2585ad 100644 --- a/packages/api/src/@core/utils/types/interface.ts +++ b/packages/api/src/@core/utils/types/interface.ts @@ -1,3 +1,4 @@ +import { Connection } from '@@core/connections/@utils/types'; import { ApiResponse, TargetObject, @@ -67,9 +68,9 @@ export interface IBaseSync { } export type SyncParam = { - linkedUserId: string; + connection: Connection; [key: string]: any; -}; +}; export interface IBaseObjectService { sync(data: SyncParam): Promise>; } diff --git a/packages/api/src/ats/activity/services/ashby/index.ts b/packages/api/src/ats/activity/services/ashby/index.ts index 664065f3c..f1ac6ed8e 100644 --- a/packages/api/src/ats/activity/services/ashby/index.ts +++ b/packages/api/src/ats/activity/services/ashby/index.ts @@ -1,17 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { IActivityService } from '@ats/activity/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; -import { ServiceRegistry } from '../registry.service'; -import { AshbyActivityInput, AshbyActivityOutput } from './types'; -import { DesunifyReturnType } from '@@core/utils/types/desunify.input'; -import { OriginalActivityOutput } from '@@core/utils/types/original/original.ats'; import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { IActivityService } from '@ats/activity/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; +import { ServiceRegistry } from '../registry.service'; +import { AshbyActivityOutput } from './types'; @Injectable() export class AshbyService implements IActivityService { @@ -29,15 +26,8 @@ export class AshbyService implements IActivityService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, candidate_id } = data; + const { connection, candidate_id } = data; if (!candidate_id) return; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const candidate = await this.prisma.ats_candidates.findUnique({ where: { id_ats_candidate: candidate_id as string, diff --git a/packages/api/src/ats/application/services/ashby/index.ts b/packages/api/src/ats/application/services/ashby/index.ts index 4e9438cd4..ddf322dee 100644 --- a/packages/api/src/ats/application/services/ashby/index.ts +++ b/packages/api/src/ats/application/services/ashby/index.ts @@ -1,17 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { IApplicationService } from '@ats/application/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { IApplicationService } from '@ats/application/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { AshbyApplicationInput, AshbyApplicationOutput } from './types'; -import { DesunifyReturnType } from '@@core/utils/types/desunify.input'; -import { OriginalApplicationOutput } from '@@core/utils/types/original/original.ats'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class AshbyService implements IApplicationService { @@ -64,15 +61,8 @@ export class AshbyService implements IApplicationService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const resp = await axios.post( `${connection.account_url}/application.list`, { diff --git a/packages/api/src/ats/candidate/services/ashby/index.ts b/packages/api/src/ats/candidate/services/ashby/index.ts index 909cfc6b3..b33bdc84c 100644 --- a/packages/api/src/ats/candidate/services/ashby/index.ts +++ b/packages/api/src/ats/candidate/services/ashby/index.ts @@ -1,15 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { ICandidateService } from '@ats/candidate/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { ICandidateService } from '@ats/candidate/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { AshbyCandidateInput, AshbyCandidateOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class AshbyService implements ICandidateService { @@ -61,15 +60,7 @@ export class AshbyService implements ICandidateService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); + const { connection } = data; const resp = await axios.post( `${connection.account_url}/candidate.list`, { diff --git a/packages/api/src/ats/department/services/ashby/index.ts b/packages/api/src/ats/department/services/ashby/index.ts index da9e293e1..2a539e6e6 100644 --- a/packages/api/src/ats/department/services/ashby/index.ts +++ b/packages/api/src/ats/department/services/ashby/index.ts @@ -1,17 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { IDepartmentService } from '@ats/department/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; -import { ServiceRegistry } from '../registry.service'; -import { AshbyDepartmentInput, AshbyDepartmentOutput } from './types'; -import { DesunifyReturnType } from '@@core/utils/types/desunify.input'; -import { OriginalDepartmentOutput } from '@@core/utils/types/original/original.ats'; import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { IDepartmentService } from '@ats/department/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; +import { ServiceRegistry } from '../registry.service'; +import { AshbyDepartmentOutput } from './types'; @Injectable() export class AshbyService implements IDepartmentService { @@ -28,15 +25,8 @@ export class AshbyService implements IDepartmentService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const resp = await axios.post( `${connection.account_url}/departement.list`, { diff --git a/packages/api/src/ats/interview/services/ashby/index.ts b/packages/api/src/ats/interview/services/ashby/index.ts index f83e0fdae..95644ea40 100644 --- a/packages/api/src/ats/interview/services/ashby/index.ts +++ b/packages/api/src/ats/interview/services/ashby/index.ts @@ -1,17 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { IInterviewService } from '@ats/interview/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; -import { ServiceRegistry } from '../registry.service'; -import { AshbyInterviewInput, AshbyInterviewOutput } from './types'; -import { DesunifyReturnType } from '@@core/utils/types/desunify.input'; -import { OriginalInterviewOutput } from '@@core/utils/types/original/original.ats'; import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { IInterviewService } from '@ats/interview/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; +import { ServiceRegistry } from '../registry.service'; +import { AshbyInterviewOutput } from './types'; @Injectable() export class AshbyService implements IInterviewService { @@ -29,15 +26,8 @@ export class AshbyService implements IInterviewService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const resp = await axios.post( `${connection.account_url}/interviewSchedule.list`, { diff --git a/packages/api/src/ats/job/services/ashby/index.ts b/packages/api/src/ats/job/services/ashby/index.ts index 2837c626e..58ab5c235 100644 --- a/packages/api/src/ats/job/services/ashby/index.ts +++ b/packages/api/src/ats/job/services/ashby/index.ts @@ -1,17 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { IJobService } from '@ats/job/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; -import { ServiceRegistry } from '../registry.service'; -import { AshbyJobInput, AshbyJobOutput } from './types'; -import { DesunifyReturnType } from '@@core/utils/types/desunify.input'; -import { OriginalJobOutput } from '@@core/utils/types/original/original.ats'; import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { IJobService } from '@ats/job/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; +import { ServiceRegistry } from '../registry.service'; +import { AshbyJobOutput } from './types'; @Injectable() export class AshbyService implements IJobService { @@ -29,15 +26,8 @@ export class AshbyService implements IJobService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const resp = await axios.post(`${connection.account_url}/job.list`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/ats/jobinterviewstage/services/ashby/index.ts b/packages/api/src/ats/jobinterviewstage/services/ashby/index.ts index f97dd4915..c66209306 100644 --- a/packages/api/src/ats/jobinterviewstage/services/ashby/index.ts +++ b/packages/api/src/ats/jobinterviewstage/services/ashby/index.ts @@ -1,20 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { IJobInterviewStageService } from '@ats/jobinterviewstage/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; -import { ServiceRegistry } from '../registry.service'; -import { - AshbyJobInterviewStageInput, - AshbyJobInterviewStageOutput, -} from './types'; -import { DesunifyReturnType } from '@@core/utils/types/desunify.input'; -import { OriginalJobInterviewStageOutput } from '@@core/utils/types/original/original.ats'; import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { IJobInterviewStageService } from '@ats/jobinterviewstage/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; +import { ServiceRegistry } from '../registry.service'; +import { AshbyJobInterviewStageOutput } from './types'; @Injectable() export class AshbyService implements IJobInterviewStageService { @@ -34,15 +28,7 @@ export class AshbyService implements IJobInterviewStageService { data: SyncParam, ): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); + const { connection } = data; const resp = await axios.post( `${connection.account_url}/interviewStage.list`, { diff --git a/packages/api/src/ats/offer/services/ashby/index.ts b/packages/api/src/ats/offer/services/ashby/index.ts index f50148e55..d0b9f4d57 100644 --- a/packages/api/src/ats/offer/services/ashby/index.ts +++ b/packages/api/src/ats/offer/services/ashby/index.ts @@ -1,17 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { IOfferService } from '@ats/offer/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; -import { ServiceRegistry } from '../registry.service'; -import { AshbyOfferInput, AshbyOfferOutput } from './types'; -import { DesunifyReturnType } from '@@core/utils/types/desunify.input'; -import { OriginalOfferOutput } from '@@core/utils/types/original/original.ats'; import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { IOfferService } from '@ats/offer/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; +import { ServiceRegistry } from '../registry.service'; +import { AshbyOfferOutput } from './types'; @Injectable() export class AshbyService implements IOfferService { @@ -29,15 +26,8 @@ export class AshbyService implements IOfferService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const resp = await axios.post(`${connection.account_url}/offer.list`, { headers: { 'Content-Type': 'offer/json', diff --git a/packages/api/src/ats/office/services/ashby/index.ts b/packages/api/src/ats/office/services/ashby/index.ts index 6223712ac..84c645a5f 100644 --- a/packages/api/src/ats/office/services/ashby/index.ts +++ b/packages/api/src/ats/office/services/ashby/index.ts @@ -1,17 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { IOfficeService } from '@ats/office/types'; -import { AtsObject } from '@ats/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; -import { ServiceRegistry } from '../registry.service'; -import { AshbyOfficeInput, AshbyOfficeOutput } from './types'; -import { DesunifyReturnType } from '@@core/utils/types/desunify.input'; -import { OriginalOfficeOutput } from '@@core/utils/types/original/original.ats'; import { SyncParam } from '@@core/utils/types/interface'; +import { AtsObject } from '@ats/@lib/@types'; +import { IOfficeService } from '@ats/office/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; +import { ServiceRegistry } from '../registry.service'; +import { AshbyOfficeOutput } from './types'; @Injectable() export class AshbyService implements IOfficeService { @@ -29,15 +26,7 @@ export class AshbyService implements IOfficeService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); + const { connection } = data; const resp = await axios.post(`${connection.account_url}/location.list`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/ats/office/sync/sync.service.ts b/packages/api/src/ats/office/sync/sync.service.ts index e58b6b3fe..a11d6747c 100644 --- a/packages/api/src/ats/office/sync/sync.service.ts +++ b/packages/api/src/ats/office/sync/sync.service.ts @@ -1,23 +1,21 @@ -import { Injectable, OnModuleInit } from '@nestjs/common'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; +import { BullQueueService } from '@@core/@core-services/queues/shared.service'; +import { CoreSyncRegistry } from '@@core/@core-services/registries/core-sync.registry'; +import { CoreUnification } from '@@core/@core-services/unification/core-unification.service'; +import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; +import { WebhookService } from '@@core/@core-services/webhooks/panora-webhooks/webhook.service'; +import { FieldMappingService } from '@@core/field-mapping/field-mapping.service'; +import { IBaseSync, SyncLinkedUserType } from '@@core/utils/types/interface'; +import { OriginalOfficeOutput } from '@@core/utils/types/original/original.ats'; +import { Injectable, OnModuleInit } from '@nestjs/common'; import { Cron } from '@nestjs/schedule'; +import { ATS_PROVIDERS } from '@panora/shared'; +import { ats_offices as AtsOffice } from '@prisma/client'; import { v4 as uuidv4 } from 'uuid'; -import { FieldMappingService } from '@@core/field-mapping/field-mapping.service'; import { ServiceRegistry } from '../services/registry.service'; -import { WebhookService } from '@@core/@core-services/webhooks/panora-webhooks/webhook.service'; -import { CoreSyncRegistry } from '@@core/@core-services/registries/core-sync.registry'; -import { ApiResponse } from '@@core/utils/types'; import { IOfficeService } from '../types'; -import { OriginalOfficeOutput } from '@@core/utils/types/original/original.ats'; import { UnifiedAtsOfficeOutput } from '../types/model.unified'; -import { ats_offices as AtsOffice } from '@prisma/client'; -import { ATS_PROVIDERS } from '@panora/shared'; -import { AtsObject } from '@ats/@lib/@types'; -import { BullQueueService } from '@@core/@core-services/queues/shared.service'; -import { IBaseSync, SyncLinkedUserType } from '@@core/utils/types/interface'; -import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; -import { CoreUnification } from '@@core/@core-services/unification/core-unification.service'; @Injectable() export class SyncService implements OnModuleInit, IBaseSync { @@ -36,7 +34,7 @@ export class SyncService implements OnModuleInit, IBaseSync { this.registry.registerService('ats', 'office', this); } onModuleInit() { -// + // } @Cron('0 */8 * * *') // every 8 hours diff --git a/packages/api/src/ats/rejectreason/services/ashby/index.ts b/packages/api/src/ats/rejectreason/services/ashby/index.ts index 31f0f9dd9..fe4182e7e 100644 --- a/packages/api/src/ats/rejectreason/services/ashby/index.ts +++ b/packages/api/src/ats/rejectreason/services/ashby/index.ts @@ -27,15 +27,8 @@ export class AshbyService implements IRejectReasonService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const resp = await axios.post( `${connection.account_url}/archiveReason.list`, { diff --git a/packages/api/src/ats/tag/services/ashby/index.ts b/packages/api/src/ats/tag/services/ashby/index.ts index 410ca03bd..796d7c19b 100644 --- a/packages/api/src/ats/tag/services/ashby/index.ts +++ b/packages/api/src/ats/tag/services/ashby/index.ts @@ -29,15 +29,8 @@ export class AshbyService implements ITagService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const resp = await axios.post( `${connection.account_url}/candidateTag.list`, { diff --git a/packages/api/src/ats/user/services/ashby/index.ts b/packages/api/src/ats/user/services/ashby/index.ts index 418605db6..94a5b3753 100644 --- a/packages/api/src/ats/user/services/ashby/index.ts +++ b/packages/api/src/ats/user/services/ashby/index.ts @@ -29,15 +29,8 @@ export class AshbyService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'ashby', - vertical: 'ats', - }, - }); const resp = await axios.post(`${connection.account_url}/user.list`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/ats/user/sync/sync.service.ts b/packages/api/src/ats/user/sync/sync.service.ts index abd89aabf..4a73eafe6 100644 --- a/packages/api/src/ats/user/sync/sync.service.ts +++ b/packages/api/src/ats/user/sync/sync.service.ts @@ -1,23 +1,21 @@ -import { Injectable, OnModuleInit } from '@nestjs/common'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; +import { BullQueueService } from '@@core/@core-services/queues/shared.service'; +import { CoreSyncRegistry } from '@@core/@core-services/registries/core-sync.registry'; +import { CoreUnification } from '@@core/@core-services/unification/core-unification.service'; +import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; +import { WebhookService } from '@@core/@core-services/webhooks/panora-webhooks/webhook.service'; +import { FieldMappingService } from '@@core/field-mapping/field-mapping.service'; +import { IBaseSync, SyncLinkedUserType } from '@@core/utils/types/interface'; +import { OriginalUserOutput } from '@@core/utils/types/original/original.ats'; +import { Injectable, OnModuleInit } from '@nestjs/common'; import { Cron } from '@nestjs/schedule'; +import { ATS_PROVIDERS } from '@panora/shared'; +import { ats_users as AtsUser } from '@prisma/client'; import { v4 as uuidv4 } from 'uuid'; -import { FieldMappingService } from '@@core/field-mapping/field-mapping.service'; import { ServiceRegistry } from '../services/registry.service'; -import { WebhookService } from '@@core/@core-services/webhooks/panora-webhooks/webhook.service'; -import { CoreSyncRegistry } from '@@core/@core-services/registries/core-sync.registry'; -import { ApiResponse } from '@@core/utils/types'; import { IUserService } from '../types'; -import { OriginalUserOutput } from '@@core/utils/types/original/original.ats'; import { UnifiedAtsUserOutput } from '../types/model.unified'; -import { ats_users as AtsUser } from '@prisma/client'; -import { ATS_PROVIDERS } from '@panora/shared'; -import { AtsObject } from '@ats/@lib/@types'; -import { BullQueueService } from '@@core/@core-services/queues/shared.service'; -import { IBaseSync, SyncLinkedUserType } from '@@core/utils/types/interface'; -import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; -import { CoreUnification } from '@@core/@core-services/unification/core-unification.service'; @Injectable() export class SyncService implements OnModuleInit, IBaseSync { @@ -36,7 +34,7 @@ export class SyncService implements OnModuleInit, IBaseSync { this.registry.registerService('ats', 'user', this); } onModuleInit() { -// + // } @Cron('0 */8 * * *') // every 8 hours diff --git a/packages/api/src/crm/company/services/attio/index.ts b/packages/api/src/crm/company/services/attio/index.ts index c47485406..a6a28d48b 100644 --- a/packages/api/src/crm/company/services/attio/index.ts +++ b/packages/api/src/crm/company/services/attio/index.ts @@ -65,15 +65,8 @@ export class AttioService implements ICompanyService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'attio', - vertical: 'crm', - }, - }); const resp = await axios.post( `${connection.account_url}/v2/objects/companies/records/query`, {}, diff --git a/packages/api/src/crm/company/services/close/index.ts b/packages/api/src/crm/company/services/close/index.ts index 096a1ecdc..a5950b3b9 100644 --- a/packages/api/src/crm/company/services/close/index.ts +++ b/packages/api/src/crm/company/services/close/index.ts @@ -63,15 +63,7 @@ export class CloseService implements ICompanyService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); + const { connection, custom_properties } = data; const commonPropertyNames = Object.keys(commonCompanyCloseProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; diff --git a/packages/api/src/crm/company/services/hubspot/index.ts b/packages/api/src/crm/company/services/hubspot/index.ts index 8363f922c..77888f546 100644 --- a/packages/api/src/crm/company/services/hubspot/index.ts +++ b/packages/api/src/crm/company/services/hubspot/index.ts @@ -1,19 +1,21 @@ -import { Injectable } from '@nestjs/common'; -import { ICompanyService } from '@crm/company/types'; -import { CrmObject } from '@crm/@lib/@types'; -import axios from 'axios'; -import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { LoggerService } from '@@core/@core-services/logger/logger.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { LoggerService } from '@@core/@core-services/logger/logger.service'; +import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { CrmObject } from '@crm/@lib/@types'; +import { ICompanyService } from '@crm/company/types'; +import { Injectable } from '@nestjs/common'; +import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { commonCompanyHubspotProperties, HubspotCompanyInput, HubspotCompanyOutput, } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; +import { RateLimit } from '@@core/rate-limit/rate-limit.decorator'; +import { RateLimitService } from '@@core/rate-limit/rate-limit.service'; +import { BullQueueService } from '@@core/@core-services/queues/shared.service'; @Injectable() export class HubspotService implements ICompanyService { @@ -22,6 +24,8 @@ export class HubspotService implements ICompanyService { private logger: LoggerService, private cryptoService: EncryptionService, private registry: ServiceRegistry, + private rateLimitService: RateLimitService, + private queues: BullQueueService, ) { this.logger.setContext( CrmObject.company.toUpperCase() + ':' + HubspotService.name, @@ -65,16 +69,10 @@ export class HubspotService implements ICompanyService { } } + @RateLimit() async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); + const { connection, custom_properties } = data; const commonPropertyNames = Object.keys(commonCompanyHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; diff --git a/packages/api/src/crm/company/services/microsoftdynamicssales/index.ts b/packages/api/src/crm/company/services/microsoftdynamicssales/index.ts index 4ff25e07d..31aacb371 100644 --- a/packages/api/src/crm/company/services/microsoftdynamicssales/index.ts +++ b/packages/api/src/crm/company/services/microsoftdynamicssales/index.ts @@ -9,103 +9,103 @@ import { EncryptionService } from '@@core/@core-services/encryption/encryption.s import { ApiResponse } from '@@core/utils/types'; import { ICompanyService } from '@crm/company/types'; import { ServiceRegistry } from '../registry.service'; -import { MicrosoftdynamicssalesCompanyInput, MicrosoftdynamicssalesCompanyOutput } from './types'; +import { + MicrosoftdynamicssalesCompanyInput, + MicrosoftdynamicssalesCompanyOutput, +} from './types'; import { SyncParam } from '@@core/utils/types/interface'; import { OriginalCompanyOutput } from '@@core/utils/types/original/original.crm'; @Injectable() export class MicrosoftdynamicssalesService implements ICompanyService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - CrmObject.company.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, - ); - this.registry.registerService('microsoftdynamicssales', this); - } - async addCompany( - companyData: MicrosoftdynamicssalesCompanyInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + CrmObject.company.toUpperCase() + + ':' + + MicrosoftdynamicssalesService.name, + ); + this.registry.registerService('microsoftdynamicssales', this); + } + async addCompany( + companyData: MicrosoftdynamicssalesCompanyInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'microsoftdynamicssales', + vertical: 'crm', + }, + }); - const respToPost = await axios.post( - `${connection.account_url}/api/data/v9.2/accounts`, - JSON.stringify(companyData), - { - headers: { - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - 'Content-Type': 'application/json', - }, - }, - ); + const respToPost = await axios.post( + `${connection.account_url}/api/data/v9.2/accounts`, + JSON.stringify(companyData), + { + headers: { + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + 'Content-Type': 'application/json', + }, + }, + ); - const postCompanyId = respToPost.headers['location'].split("/").pop(); - // console.log(res.headers['location'].split('(')[1].split(')')[0]) + const postCompanyId = respToPost.headers['location'].split('/').pop(); + // console.log(res.headers['location'].split('(')[1].split(')')[0]) - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/${postCompanyId}`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/${postCompanyId}`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); - return { - data: resp.data, - message: 'Microsoftdynamicssales company created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + return { + data: resp.data, + message: 'Microsoftdynamicssales company created', + statusCode: 201, + }; + } catch (error) { + throw error; } + } - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; + async sync( + data: SyncParam, + ): Promise> { + try { + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/accounts`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - return { - data: resp.data.value, - message: 'Microsoftdynamicssales companies retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/accounts`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + return { + data: resp.data.value, + message: 'Microsoftdynamicssales companies retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/crm/company/services/pipedrive/index.ts b/packages/api/src/crm/company/services/pipedrive/index.ts index 4971369d3..377a78529 100644 --- a/packages/api/src/crm/company/services/pipedrive/index.ts +++ b/packages/api/src/crm/company/services/pipedrive/index.ts @@ -60,14 +60,8 @@ export class PipedriveService implements ICompanyService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); + const { connection } = data; + const resp = await axios.get( `${connection.account_url}/v1/organizations`, { diff --git a/packages/api/src/crm/company/services/salesforce/index.ts b/packages/api/src/crm/company/services/salesforce/index.ts index bdfd56f44..4b1fbfbc0 100644 --- a/packages/api/src/crm/company/services/salesforce/index.ts +++ b/packages/api/src/crm/company/services/salesforce/index.ts @@ -8,10 +8,10 @@ import { EncryptionService } from '@@core/@core-services/encryption/encryption.s import { ApiResponse } from '@@core/utils/types'; import { ServiceRegistry } from '../registry.service'; import { - commonSalesforceCompanyProperties, - SalesforceCompanyInput, - SalesforceCompanyOutput, - } from './types'; + commonSalesforceCompanyProperties, + SalesforceCompanyInput, + SalesforceCompanyOutput, +} from './types'; import { SyncParam } from '@@core/utils/types/interface'; @Injectable() @@ -67,32 +67,27 @@ export class SalesforceService implements ICompanyService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties, pageSize, cursor } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'salesforce', - vertical: 'crm', - }, - }); - + const { connection, custom_properties, pageSize, cursor } = data; const instanceUrl = connection.account_url; - let pagingString = `${pageSize ? `ORDER BY Id DESC LIMIT ${pageSize} ` : ''}${ - cursor ? `OFFSET ${cursor}` : '' - }`; + let pagingString = `${ + pageSize ? `ORDER BY Id DESC LIMIT ${pageSize} ` : '' + }${cursor ? `OFFSET ${cursor}` : ''}`; if (!pageSize && !cursor) { pagingString = 'LIMIT 200'; } - const commonPropertyNames = Object.keys(commonSalesforceCompanyProperties); + const commonPropertyNames = Object.keys( + commonSalesforceCompanyProperties, + ); const allProperties = [...commonPropertyNames, ...custom_properties]; const fields = allProperties.join(','); const query = `SELECT ${fields} FROM Account ${pagingString}`; const resp = await axios.get( - `${instanceUrl}/services/data/v56.0/query/?q=${encodeURIComponent(query)}`, + `${instanceUrl}/services/data/v56.0/query/?q=${encodeURIComponent( + query, + )}`, { headers: { Authorization: `Bearer ${this.cryptoService.decrypt( @@ -113,4 +108,4 @@ export class SalesforceService implements ICompanyService { throw error; } } -} \ No newline at end of file +} diff --git a/packages/api/src/crm/company/services/zendesk/index.ts b/packages/api/src/crm/company/services/zendesk/index.ts index 294f877f5..d86dba397 100644 --- a/packages/api/src/crm/company/services/zendesk/index.ts +++ b/packages/api/src/crm/company/services/zendesk/index.ts @@ -63,14 +63,8 @@ export class ZendeskService implements ICompanyService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'crm', - }, - }); + const { connection } = data; + const resp = await axios.get(`${connection.account_url}/v2/contacts`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/company/services/zoho/index.ts b/packages/api/src/crm/company/services/zoho/index.ts index 2ca931b3d..9a1c6b320 100644 --- a/packages/api/src/crm/company/services/zoho/index.ts +++ b/packages/api/src/crm/company/services/zoho/index.ts @@ -72,14 +72,8 @@ export class ZohoService implements ICompanyService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zoho', - vertical: 'crm', - }, - }); + const { connection } = data; + const fields = 'Owner,Industry,Billing_Street,Billing_Code,Billing_City,Billing_State,Employees,Phone,Description,Account_Name'; const resp = await axios.get( diff --git a/packages/api/src/crm/company/sync/sync.service.ts b/packages/api/src/crm/company/sync/sync.service.ts index 05f5a4927..b88a80817 100644 --- a/packages/api/src/crm/company/sync/sync.service.ts +++ b/packages/api/src/crm/company/sync/sync.service.ts @@ -32,7 +32,7 @@ export class SyncService implements OnModuleInit, IBaseSync { this.registry.registerService('crm', 'company', this); } onModuleInit() { -// + // } //function used by sync worker which populate our crm_companies table diff --git a/packages/api/src/crm/contact/services/attio/index.ts b/packages/api/src/crm/contact/services/attio/index.ts index 3c98594f2..f41c1db1f 100644 --- a/packages/api/src/crm/contact/services/attio/index.ts +++ b/packages/api/src/crm/contact/services/attio/index.ts @@ -64,15 +64,7 @@ export class AttioService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'attio', - vertical: 'crm', - }, - }); + const { connection } = data; const resp = await axios.post( `${connection.account_url}/v2/objects/people/records/query`, diff --git a/packages/api/src/crm/contact/services/close/index.ts b/packages/api/src/crm/contact/services/close/index.ts index 28a6aa92b..7f1ffe17a 100644 --- a/packages/api/src/crm/contact/services/close/index.ts +++ b/packages/api/src/crm/contact/services/close/index.ts @@ -61,15 +61,7 @@ export class CloseService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); + const { connection } = data; const baseURL = `${connection.account_url}/v1/contact`; diff --git a/packages/api/src/crm/contact/services/hubspot/index.ts b/packages/api/src/crm/contact/services/hubspot/index.ts index a5daf4499..a3952943e 100644 --- a/packages/api/src/crm/contact/services/hubspot/index.ts +++ b/packages/api/src/crm/contact/services/hubspot/index.ts @@ -67,15 +67,7 @@ export class HubspotService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); + const { connection, custom_properties } = data; const commonPropertyNames = Object.keys(commonHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; diff --git a/packages/api/src/crm/contact/services/microsoftdynamicssales/index.ts b/packages/api/src/crm/contact/services/microsoftdynamicssales/index.ts index caeeb9891..9a048bafd 100644 --- a/packages/api/src/crm/contact/services/microsoftdynamicssales/index.ts +++ b/packages/api/src/crm/contact/services/microsoftdynamicssales/index.ts @@ -8,105 +8,104 @@ import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { ApiResponse } from '@@core/utils/types'; import { ServiceRegistry } from '../registry.service'; -import { MicrosoftdynamicssalesContactInput, MicrosoftdynamicssalesContactOutput } from './types'; +import { + MicrosoftdynamicssalesContactInput, + MicrosoftdynamicssalesContactOutput, +} from './types'; import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class MicrosoftdynamicssalesService implements IContactService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - CrmObject.contact.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, - ); - this.registry.registerService('microsoftdynamicssales', this); - } + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + CrmObject.contact.toUpperCase() + + ':' + + MicrosoftdynamicssalesService.name, + ); + this.registry.registerService('microsoftdynamicssales', this); + } - async addContact( - contactData: MicrosoftdynamicssalesContactInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); + async addContact( + contactData: MicrosoftdynamicssalesContactInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'microsoftdynamicssales', + vertical: 'crm', + }, + }); - const respToPost = await axios.post( - `${connection.account_url}/api/data/v9.2/contacts`, - JSON.stringify(contactData), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); + const respToPost = await axios.post( + `${connection.account_url}/api/data/v9.2/contacts`, + JSON.stringify(contactData), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); - const postContactId = respToPost.headers['location'].split("/").pop(); + const postContactId = respToPost.headers['location'].split('/').pop(); - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/${postContactId}`, - { - headers: { - accept: 'application/json', - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - return { - data: resp.data, - message: 'microsoftdynamicssales contact created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/${postContactId}`, + { + headers: { + accept: 'application/json', + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + return { + data: resp.data, + message: 'microsoftdynamicssales contact created', + statusCode: 201, + }; + } catch (error) { + throw error; } + } - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); + async sync( + data: SyncParam, + ): Promise> { + try { + const { connection } = data; - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/contacts`, - { - headers: { - accept: 'application/json', - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/contacts`, + { + headers: { + accept: 'application/json', + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); - return { - data: resp.data.value, - message: 'Microsoftdynamicssales contacts retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + return { + data: resp.data.value, + message: 'Microsoftdynamicssales contacts retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/crm/contact/services/pipedrive/index.ts b/packages/api/src/crm/contact/services/pipedrive/index.ts index 3c217e2fa..efafb0bf7 100644 --- a/packages/api/src/crm/contact/services/pipedrive/index.ts +++ b/packages/api/src/crm/contact/services/pipedrive/index.ts @@ -62,15 +62,8 @@ export class PipedriveService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); const resp = await axios.get(`${connection.account_url}/v1/persons`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/contact/services/salesforce/index.ts b/packages/api/src/crm/contact/services/salesforce/index.ts index 47904f087..f080a92d2 100644 --- a/packages/api/src/crm/contact/services/salesforce/index.ts +++ b/packages/api/src/crm/contact/services/salesforce/index.ts @@ -63,15 +63,7 @@ export class SalesforceService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties, pageSize, cursor } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'salesforce', - vertical: 'crm', - }, - }); + const { connection, custom_properties, pageSize, cursor } = data; const instanceUrl = connection.account_url; let pagingString = ''; diff --git a/packages/api/src/crm/contact/services/zendesk/index.ts b/packages/api/src/crm/contact/services/zendesk/index.ts index 92fd5ac40..747d8ea3b 100644 --- a/packages/api/src/crm/contact/services/zendesk/index.ts +++ b/packages/api/src/crm/contact/services/zendesk/index.ts @@ -64,15 +64,8 @@ export class ZendeskService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'crm', - }, - }); const resp = await axios.get(`${connection.account_url}/v2/contacts`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/contact/services/zoho/index.ts b/packages/api/src/crm/contact/services/zoho/index.ts index b9be1c35d..102dea99b 100644 --- a/packages/api/src/crm/contact/services/zoho/index.ts +++ b/packages/api/src/crm/contact/services/zoho/index.ts @@ -73,15 +73,8 @@ export class ZohoService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zoho', - vertical: 'crm', - }, - }); const fields = 'First_Name,Last_Name,Full_Name,Email,Phone,Mailing_Street,Other_Street,Mailing_City,Other_City,Mailing_State,Other_State,Mailing_Zip,Other_Zip,Mailing_Country,Other_Country'; const resp = await axios.get( diff --git a/packages/api/src/crm/deal/services/attio/index.ts b/packages/api/src/crm/deal/services/attio/index.ts index 09ec6e3eb..02426f280 100644 --- a/packages/api/src/crm/deal/services/attio/index.ts +++ b/packages/api/src/crm/deal/services/attio/index.ts @@ -64,15 +64,8 @@ export class AttioService implements IDealService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'attio', - vertical: 'crm', - }, - }); const resp = await axios.post( `${connection.account_url}/v2/objects/deals/records/query`, {}, diff --git a/packages/api/src/crm/deal/services/close/index.ts b/packages/api/src/crm/deal/services/close/index.ts index 395b3009f..4caf8f47f 100644 --- a/packages/api/src/crm/deal/services/close/index.ts +++ b/packages/api/src/crm/deal/services/close/index.ts @@ -60,16 +60,7 @@ export class CloseService implements IDealService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - //crm.schemas.deals.read","crm.objects.deals.read - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); + const { connection } = data; const baseURL = `${connection.account_url}/v1/opportunity`; const resp = await axios.get(baseURL, { diff --git a/packages/api/src/crm/deal/services/hubspot/index.ts b/packages/api/src/crm/deal/services/hubspot/index.ts index 8022cfe5e..6ae560d27 100644 --- a/packages/api/src/crm/deal/services/hubspot/index.ts +++ b/packages/api/src/crm/deal/services/hubspot/index.ts @@ -68,16 +68,9 @@ export class HubspotService implements IDealService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties } = data; + const { connection, custom_properties } = data; //crm.schemas.deals.read","crm.objects.deals.read - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); const commonPropertyNames = Object.keys(commonDealHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; diff --git a/packages/api/src/crm/deal/services/microsoftdynamicssales/index.ts b/packages/api/src/crm/deal/services/microsoftdynamicssales/index.ts index fd93e9d74..17d4e6050 100644 --- a/packages/api/src/crm/deal/services/microsoftdynamicssales/index.ts +++ b/packages/api/src/crm/deal/services/microsoftdynamicssales/index.ts @@ -8,107 +8,101 @@ import { EncryptionService } from '@@core/@core-services/encryption/encryption.s import { ApiResponse } from '@@core/utils/types'; import { IDealService } from '@crm/deal/types'; import { ServiceRegistry } from '../registry.service'; -import { MicrosoftdynamicssalesDealInput, MicrosoftdynamicssalesDealOutput } from './types'; +import { + MicrosoftdynamicssalesDealInput, + MicrosoftdynamicssalesDealOutput, +} from './types'; import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class MicrosoftdynamicssalesService implements IDealService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - CrmObject.deal.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, - ); - this.registry.registerService('microsoftdynamicssales', this); - } - async addDeal( - dealData: MicrosoftdynamicssalesDealInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - - const respToPost = await axios.post( - `${connection.account_url}/api/data/v9.2/opportunities`, - JSON.stringify(dealData), - { - headers: { - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - 'Content-Type': 'application/json', - }, - }, - ); - - const postDealId = respToPost.headers['location'].split("/").pop(); - - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/${postDealId}`, - { - headers: { - accept: 'application/json', - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + CrmObject.deal.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, + ); + this.registry.registerService('microsoftdynamicssales', this); + } + async addDeal( + dealData: MicrosoftdynamicssalesDealInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'microsoftdynamicssales', + vertical: 'crm', + }, + }); + const respToPost = await axios.post( + `${connection.account_url}/api/data/v9.2/opportunities`, + JSON.stringify(dealData), + { + headers: { + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + 'Content-Type': 'application/json', + }, + }, + ); + const postDealId = respToPost.headers['location'].split('/').pop(); + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/${postDealId}`, + { + headers: { + accept: 'application/json', + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); - return { - data: resp.data, - message: 'Microsoftdynamicssales deal created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + return { + data: resp.data, + message: 'Microsoftdynamicssales deal created', + statusCode: 201, + }; + } catch (error) { + throw error; } + } - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; + async sync( + data: SyncParam, + ): Promise> { + try { + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/opportunities`, - { - headers: { - accept: 'application/json', - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - return { - data: resp.data.value, - message: 'Microsoftdynamicssales deals retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/opportunities`, + { + headers: { + accept: 'application/json', + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + return { + data: resp.data.value, + message: 'Microsoftdynamicssales deals retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/crm/deal/services/pipedrive/index.ts b/packages/api/src/crm/deal/services/pipedrive/index.ts index 37ddb9f63..0d764a9d6 100644 --- a/packages/api/src/crm/deal/services/pipedrive/index.ts +++ b/packages/api/src/crm/deal/services/pipedrive/index.ts @@ -61,14 +61,8 @@ export class PipedriveService implements IDealService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); + const { connection } = data; + const resp = await axios.get(`${connection.account_url}/v1/deals`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/deal/services/salesforce/index.ts b/packages/api/src/crm/deal/services/salesforce/index.ts index 9ae3c581f..165e0783c 100644 --- a/packages/api/src/crm/deal/services/salesforce/index.ts +++ b/packages/api/src/crm/deal/services/salesforce/index.ts @@ -69,20 +69,12 @@ export class SalesforceService implements IDealService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties, pageSize, cursor } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'salesforce', - vertical: 'crm', - }, - }); + const { connection, custom_properties, pageSize, cursor } = data; const instanceUrl = connection.account_url; - let pagingString = `${pageSize ? `ORDER BY Id DESC LIMIT ${pageSize} ` : ''}${ - cursor ? `OFFSET ${cursor}` : '' - }`; + let pagingString = `${ + pageSize ? `ORDER BY Id DESC LIMIT ${pageSize} ` : '' + }${cursor ? `OFFSET ${cursor}` : ''}`; if (!pageSize && !cursor) { pagingString = 'LIMIT 200'; } @@ -94,7 +86,9 @@ export class SalesforceService implements IDealService { const query = `SELECT ${fields} FROM Opportunity ${pagingString}`; const resp = await axios.get( - `${instanceUrl}/services/data/v56.0/query/?q=${encodeURIComponent(query)}`, + `${instanceUrl}/services/data/v56.0/query/?q=${encodeURIComponent( + query, + )}`, { headers: { Authorization: `Bearer ${this.cryptoService.decrypt( @@ -115,4 +109,4 @@ export class SalesforceService implements IDealService { throw error; } } -} \ No newline at end of file +} diff --git a/packages/api/src/crm/deal/services/zendesk/index.ts b/packages/api/src/crm/deal/services/zendesk/index.ts index 67a3250d6..05a632d7c 100644 --- a/packages/api/src/crm/deal/services/zendesk/index.ts +++ b/packages/api/src/crm/deal/services/zendesk/index.ts @@ -63,15 +63,8 @@ export class ZendeskService implements IDealService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'crm', - }, - }); const resp = await axios.get(`${connection.account_url}/v2/deals`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/deal/services/zoho/index.ts b/packages/api/src/crm/deal/services/zoho/index.ts index f7a10e8db..b8f0df9e2 100644 --- a/packages/api/src/crm/deal/services/zoho/index.ts +++ b/packages/api/src/crm/deal/services/zoho/index.ts @@ -71,15 +71,8 @@ export class ZohoService implements IDealService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zoho', - vertical: 'crm', - }, - }); const fields = 'Owner,Description,Deal_Name,Account_Name,Stage,Amount,Contact_Name'; const resp = await axios.get( diff --git a/packages/api/src/crm/engagement/services/close/index.ts b/packages/api/src/crm/engagement/services/close/index.ts index ea97c74b4..0f29b28d0 100644 --- a/packages/api/src/crm/engagement/services/close/index.ts +++ b/packages/api/src/crm/engagement/services/close/index.ts @@ -18,6 +18,7 @@ import { CloseEngagementMeetingOutput, CloseEngagementOutput, } from './types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class CloseService implements IEngagementService { @@ -170,15 +171,15 @@ export class CloseService implements IEngagementService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, engagement_type } = data; + const { connection, engagement_type } = data; switch (engagement_type as string) { case 'CALL': - return this.syncCalls(linkedUserId); + return this.syncCalls(connection); case 'MEETING': - return this.syncMeetings(linkedUserId); + return this.syncMeetings(connection); case 'EMAIL': - return this.syncEmails(linkedUserId); + return this.syncEmails(connection); default: break; } @@ -187,16 +188,8 @@ export class CloseService implements IEngagementService { } } - private async syncCalls(linkedUserId: string) { + private async syncCalls(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); - const baseURL = `${connection.account_url}/activity/call`; const resp = await axios.get(baseURL, { @@ -219,16 +212,8 @@ export class CloseService implements IEngagementService { } } - private async syncMeetings(linkedUserId: string) { + private async syncMeetings(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); - const baseURL = `${connection.account_url}/activity/meeting`; const resp = await axios.get(baseURL, { @@ -250,16 +235,8 @@ export class CloseService implements IEngagementService { } } - private async syncEmails(linkedUserId: string) { + private async syncEmails(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); - const baseURL = `${connection.account_url}/activity/email`; const resp = await axios.get(baseURL, { headers: { diff --git a/packages/api/src/crm/engagement/services/hubspot/index.ts b/packages/api/src/crm/engagement/services/hubspot/index.ts index eff454ecb..50c7d248c 100644 --- a/packages/api/src/crm/engagement/services/hubspot/index.ts +++ b/packages/api/src/crm/engagement/services/hubspot/index.ts @@ -21,6 +21,7 @@ import { commonEmailHubspotProperties, commonMeetingHubspotProperties, } from './types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class HubspotService implements IEngagementService { @@ -178,15 +179,15 @@ export class HubspotService implements IEngagementService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties, engagement_type } = data; + const { connection, custom_properties, engagement_type } = data; switch (engagement_type as string) { case 'CALL': - return this.syncCalls(linkedUserId, custom_properties); + return this.syncCalls(connection, custom_properties); case 'MEETING': - return this.syncMeetings(linkedUserId, custom_properties); + return this.syncMeetings(connection, custom_properties); case 'EMAIL': - return this.syncEmails(linkedUserId, custom_properties); + return this.syncEmails(connection, custom_properties); default: break; } @@ -195,16 +196,11 @@ export class HubspotService implements IEngagementService { } } - private async syncCalls(linkedUserId: string, custom_properties?: string[]) { + private async syncCalls( + connection: Connection, + custom_properties?: string[], + ) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); - const commonPropertyNames = Object.keys(commonCallHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; const baseURL = `${connection.account_url}/crm/v3/objects/call`; @@ -236,18 +232,10 @@ export class HubspotService implements IEngagementService { } private async syncMeetings( - linkedUserId: string, + connection: Connection, custom_properties?: string[], ) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); - const commonPropertyNames = Object.keys(commonMeetingHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; const baseURL = `${connection.account_url}/crm/v3/objects/meeting`; @@ -278,16 +266,11 @@ export class HubspotService implements IEngagementService { } } - private async syncEmails(linkedUserId: string, custom_properties?: string[]) { + private async syncEmails( + connection: Connection, + custom_properties?: string[], + ) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); - const commonPropertyNames = Object.keys(commonEmailHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; const baseURL = `${connection.account_url}/crm/v3/objects/emails`; diff --git a/packages/api/src/crm/engagement/services/microsoftdynamicssales/index.ts b/packages/api/src/crm/engagement/services/microsoftdynamicssales/index.ts index 27c89a3a6..361c5204c 100644 --- a/packages/api/src/crm/engagement/services/microsoftdynamicssales/index.ts +++ b/packages/api/src/crm/engagement/services/microsoftdynamicssales/index.ts @@ -9,353 +9,344 @@ import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { - MicrosoftdynamicssalesEngagementAppointmentInput, - MicrosoftdynamicssalesEngagementAppointmentOutput, - MicrosoftdynamicssalesEngagementCallInput, - MicrosoftdynamicssalesEngagementCallOutput, - MicrosoftdynamicssalesEngagementEmailInput, - MicrosoftdynamicssalesEngagementEmailOutput, - MicrosoftdynamicssalesEngagementInput, - MicrosoftdynamicssalesEngagementOutput + MicrosoftdynamicssalesEngagementAppointmentInput, + MicrosoftdynamicssalesEngagementAppointmentOutput, + MicrosoftdynamicssalesEngagementCallInput, + MicrosoftdynamicssalesEngagementCallOutput, + MicrosoftdynamicssalesEngagementEmailInput, + MicrosoftdynamicssalesEngagementEmailOutput, + MicrosoftdynamicssalesEngagementInput, + MicrosoftdynamicssalesEngagementOutput, } from './types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class MicrosoftdynamicssalesService implements IEngagementService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - CrmObject.engagement.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, - ); - this.registry.registerService('microsoftdynamicssales', this); + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + CrmObject.engagement.toUpperCase() + + ':' + + MicrosoftdynamicssalesService.name, + ); + this.registry.registerService('microsoftdynamicssales', this); + } + async addEngagement( + engagementData: MicrosoftdynamicssalesEngagementInput, + linkedUserId: string, + engagement_type: string, + ): Promise> { + try { + switch (engagement_type) { + case 'CALL': + return this.addCall( + engagementData as MicrosoftdynamicssalesEngagementCallInput, + linkedUserId, + ); + case 'MEETING': + return this.addMeeting( + engagementData as MicrosoftdynamicssalesEngagementAppointmentInput, + linkedUserId, + ); + case 'EMAIL': + return this.addEmail( + engagementData as MicrosoftdynamicssalesEngagementEmailInput, + linkedUserId, + ); + default: + break; + } + } catch (error) { + throw error; } - async addEngagement( - engagementData: MicrosoftdynamicssalesEngagementInput, - linkedUserId: string, - engagement_type: string, - ): Promise> { - try { - switch (engagement_type) { - case 'CALL': - return this.addCall( - engagementData as MicrosoftdynamicssalesEngagementCallInput, - linkedUserId, - ); - case 'MEETING': - return this.addMeeting( - engagementData as MicrosoftdynamicssalesEngagementAppointmentInput, - linkedUserId, - ); - case 'EMAIL': - return this.addEmail( - engagementData as MicrosoftdynamicssalesEngagementEmailInput, - linkedUserId, - ); - default: - break; - } - } catch (error) { - throw error; - } + } + + private async addCall( + engagementData: MicrosoftdynamicssalesEngagementCallInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'microsoftdynamicssales', + vertical: 'crm', + }, + }); + + const respToPost = await axios.post( + `${connection.account_url}/api/data/v9.2/phonecalls`, + JSON.stringify(engagementData), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + + const postCallId = respToPost.headers['location'].split('/').pop(); + + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/${postCallId}`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + + return { + data: resp.data, + message: 'Microsoftdynamicssales call created', + statusCode: 201, + }; + } catch (error) { + throw error; } - - private async addCall( - engagementData: MicrosoftdynamicssalesEngagementCallInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - - const respToPost = await axios.post( - `${connection.account_url}/api/data/v9.2/phonecalls`, - JSON.stringify(engagementData), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - - const postCallId = respToPost.headers['location'].split("/").pop(); - - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/${postCallId}`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - - return { - data: resp.data, - message: 'Microsoftdynamicssales call created', - statusCode: 201, - }; - } catch (error) { - throw error; - } - } - - private async addMeeting( - engagementData: MicrosoftdynamicssalesEngagementAppointmentInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - - const respToPost = await axios.post( - `${connection.account_url}/api/data/v9.2/appointments`, - JSON.stringify(engagementData), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - - const postAppointmentId = respToPost.headers['location'].split("/").pop(); - - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/${postAppointmentId}`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - - - return { - data: resp.data, - message: 'Microsoftdynamicssales meeting created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + } + + private async addMeeting( + engagementData: MicrosoftdynamicssalesEngagementAppointmentInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'microsoftdynamicssales', + vertical: 'crm', + }, + }); + + const respToPost = await axios.post( + `${connection.account_url}/api/data/v9.2/appointments`, + JSON.stringify(engagementData), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + + const postAppointmentId = respToPost.headers['location'].split('/').pop(); + + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/${postAppointmentId}`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + + return { + data: resp.data, + message: 'Microsoftdynamicssales meeting created', + statusCode: 201, + }; + } catch (error) { + throw error; } - - private async addEmail( - engagementData: MicrosoftdynamicssalesEngagementEmailInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - - const respToPost = await axios.post( - `${connection.account_url}/api/data/v9.2/emails`, - JSON.stringify(engagementData), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - - const postEmailId = respToPost.headers['location'].split("/").pop(); - - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/${postEmailId}`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - - - return { - data: resp.data, - message: 'Microsoftdynamicssales email created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + } + + private async addEmail( + engagementData: MicrosoftdynamicssalesEngagementEmailInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'microsoftdynamicssales', + vertical: 'crm', + }, + }); + + const respToPost = await axios.post( + `${connection.account_url}/api/data/v9.2/emails`, + JSON.stringify(engagementData), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + + const postEmailId = respToPost.headers['location'].split('/').pop(); + + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/${postEmailId}`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + + return { + data: resp.data, + message: 'Microsoftdynamicssales email created', + statusCode: 201, + }; + } catch (error) { + throw error; } - - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId, custom_properties, engagement_type } = data; - - switch (engagement_type as string) { - case 'CALL': - return this.syncCalls(linkedUserId, custom_properties); - case 'MEETING': - return this.syncMeetings(linkedUserId, custom_properties); - case 'EMAIL': - return this.syncEmails(linkedUserId, custom_properties); - default: - break; - } - } catch (error) { - throw error; - } + } + + async sync( + data: SyncParam, + ): Promise> { + try { + const { connection, custom_properties, engagement_type } = data; + + switch (engagement_type as string) { + case 'CALL': + return this.syncCalls(connection, custom_properties); + case 'MEETING': + return this.syncMeetings(connection, custom_properties); + case 'EMAIL': + return this.syncEmails(connection, custom_properties); + default: + break; + } + } catch (error) { + throw error; } - - private async syncCalls(linkedUserId: string, custom_properties?: string[]) { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - - // const commonPropertyNames = Object.keys(commonCallMicrosoftdynamicssaleProperties); - // const allProperties = [...commonPropertyNames, ...custom_properties]; - // const baseURL = 'https://api.hubapi.com/crm/v3/objects/calls'; - - // const queryString = allProperties - // .map((prop) => `properties=${encodeURIComponent(prop)}`) - // .join('&'); - - // const url = `${baseURL}?${queryString}`; - - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/phonecalls`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Synced microsoftdynamicssales engagements calls !`); - - return { - data: resp.data.value, - message: 'Microsoftdynamicssales engagements calls retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + } + + private async syncCalls( + connection: Connection, + custom_properties?: string[], + ) { + try { + // const commonPropertyNames = Object.keys(commonCallMicrosoftdynamicssaleProperties); + // const allProperties = [...commonPropertyNames, ...custom_properties]; + // const baseURL = 'https://api.hubapi.com/crm/v3/objects/calls'; + + // const queryString = allProperties + // .map((prop) => `properties=${encodeURIComponent(prop)}`) + // .join('&'); + + // const url = `${baseURL}?${queryString}`; + + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/phonecalls`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + this.logger.log(`Synced microsoftdynamicssales engagements calls !`); + + return { + data: resp.data.value, + message: 'Microsoftdynamicssales engagements calls retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } - - private async syncMeetings( - linkedUserId: string, - custom_properties?: string[], - ) { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - - // const commonPropertyNames = Object.keys(commonMeetingMicrosoftdynamicssaleProperties); - // const allProperties = [...commonPropertyNames, ...custom_properties]; - // const baseURL = 'https://api.hubapi.com/crm/v3/objects/meetings'; - - // const queryString = allProperties - // .map((prop) => `properties=${encodeURIComponent(prop)}`) - // .join('&'); - - // const url = `${baseURL}?${queryString}`; - - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/appointments`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Synced microsoftdynamicssales engagements meetings !`); - - return { - data: resp.data.value, - message: 'Microsoftdynamicssales engagements meetings retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + } + + private async syncMeetings( + connection: Connection, + custom_properties?: string[], + ) { + try { + // const commonPropertyNames = Object.keys(commonMeetingMicrosoftdynamicssaleProperties); + // const allProperties = [...commonPropertyNames, ...custom_properties]; + // const baseURL = 'https://api.hubapi.com/crm/v3/objects/meetings'; + + // const queryString = allProperties + // .map((prop) => `properties=${encodeURIComponent(prop)}`) + // .join('&'); + + // const url = `${baseURL}?${queryString}`; + + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/appointments`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + this.logger.log(`Synced microsoftdynamicssales engagements meetings !`); + + return { + data: resp.data.value, + message: 'Microsoftdynamicssales engagements meetings retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } - - private async syncEmails(linkedUserId: string, custom_properties?: string[]) { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - - // const commonPropertyNames = Object.keys(commonEmailMicrosoftdynamicssaleProperties); - // const allProperties = [...commonPropertyNames, ...custom_properties]; - // const baseURL = 'https://api.hubapi.com/crm/v3/objects/emails'; - - // const queryString = allProperties - // .map((prop) => `properties=${encodeURIComponent(prop)}`) - // .join('&'); - - // const url = `${baseURL}?${queryString}`; - - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/emails`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Synced microsoftdynamicssales engagements emails !`); - - return { - data: resp.data.value, - message: 'Microsoftdynamicssales engagements emails retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + } + + private async syncEmails( + connection: Connection, + custom_properties?: string[], + ) { + try { + // const commonPropertyNames = Object.keys(commonEmailMicrosoftdynamicssaleProperties); + // const allProperties = [...commonPropertyNames, ...custom_properties]; + // const baseURL = 'https://api.hubapi.com/crm/v3/objects/emails'; + + // const queryString = allProperties + // .map((prop) => `properties=${encodeURIComponent(prop)}`) + // .join('&'); + + // const url = `${baseURL}?${queryString}`; + + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/emails`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + this.logger.log(`Synced microsoftdynamicssales engagements emails !`); + + return { + data: resp.data.value, + message: 'Microsoftdynamicssales engagements emails retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/crm/engagement/services/pipedrive/index.ts b/packages/api/src/crm/engagement/services/pipedrive/index.ts index 21d3573d9..4580d06af 100644 --- a/packages/api/src/crm/engagement/services/pipedrive/index.ts +++ b/packages/api/src/crm/engagement/services/pipedrive/index.ts @@ -9,6 +9,7 @@ import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { PipedriveEngagementInput, PipedriveEngagementOutput } from './types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class PipedriveService implements IEngagementService { constructor( @@ -62,15 +63,15 @@ export class PipedriveService implements IEngagementService { data: SyncParam, ): Promise> { try { - const { linkedUserId, engagement_type } = data; + const { connection, engagement_type } = data; switch (engagement_type as string) { case 'CALL': - return this.syncCalls(linkedUserId); + return this.syncCalls(connection); case 'MEETING': - return this.syncMeetings(linkedUserId); + return this.syncMeetings(connection); case 'EMAIL': - return this.syncEmails(linkedUserId); + return this.syncEmails(connection); default: break; } @@ -79,16 +80,8 @@ export class PipedriveService implements IEngagementService { } } - private async syncCalls(linkedUserId: string) { + private async syncCalls(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); - const resp = await axios.get(`${connection.account_url}/v1/activities`, { headers: { 'Content-Type': 'application/json', @@ -112,16 +105,8 @@ export class PipedriveService implements IEngagementService { throw error; } } - private async syncMeetings(linkedUserId: string) { + private async syncMeetings(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); - const resp = await axios.get(`${connection.account_url}/v1/activities`, { headers: { 'Content-Type': 'application/json', @@ -145,16 +130,8 @@ export class PipedriveService implements IEngagementService { throw error; } } - private async syncEmails(linkedUserId: string) { + private async syncEmails(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); - const resp = await axios.get(`${connection.account_url}/v1/activities`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/engagement/services/zendesk/index.ts b/packages/api/src/crm/engagement/services/zendesk/index.ts index 09386ea1b..8dcc2096f 100644 --- a/packages/api/src/crm/engagement/services/zendesk/index.ts +++ b/packages/api/src/crm/engagement/services/zendesk/index.ts @@ -9,6 +9,7 @@ import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { ZendeskEngagementInput, ZendeskEngagementOutput } from './types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class ZendeskService implements IEngagementService { constructor( @@ -83,11 +84,11 @@ export class ZendeskService implements IEngagementService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, engagement_type } = data; + const { connection, engagement_type } = data; switch (engagement_type as string) { case 'CALL': - return this.syncCalls(linkedUserId); + return this.syncCalls(connection); case 'MEETING': return; case 'EMAIL': @@ -100,16 +101,8 @@ export class ZendeskService implements IEngagementService { } } - private async syncCalls(linkedUserId: string) { + private async syncCalls(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'crm', - }, - }); - const resp = await axios.get(`${connection.account_url}/v2/calls`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/engagement/services/zoho/index.ts b/packages/api/src/crm/engagement/services/zoho/index.ts index 7748a9a03..468a22d3e 100644 --- a/packages/api/src/crm/engagement/services/zoho/index.ts +++ b/packages/api/src/crm/engagement/services/zoho/index.ts @@ -9,6 +9,7 @@ import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { ZohoEngagementOutput } from './types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class ZohoService implements IEngagementService { @@ -24,15 +25,8 @@ export class ZohoService implements IEngagementService { this.registry.registerService('zoho', this); } - private async syncCalls(linkedUserId: string) { + private async syncCalls(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zoho', - vertical: 'crm', - }, - }); const fields = 'Owner,Description,Campaign_Name,End_Date,Start_Date,Type,Created_By,Subject,Call_Type,Who_Id, Call_Start_Time, Call_Duration'; const resp = await axios.get( @@ -57,15 +51,8 @@ export class ZohoService implements IEngagementService { } } - private async syncMeetings(linkedUserId: string) { + private async syncMeetings(connection: Connection) { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zoho', - vertical: 'crm', - }, - }); const fields = 'Owner,Description,End_DateTime,Start_DateTime,Subject,What_Id,Who_Id,Participants,Event_Title'; const resp = await axios.get( @@ -92,13 +79,13 @@ export class ZohoService implements IEngagementService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, engagement_type } = data; + const { connection, engagement_type } = data; switch (engagement_type as string) { case 'CALL': - return this.syncCalls(linkedUserId); + return this.syncCalls(connection); case 'MEETING': - return this.syncMeetings(linkedUserId); + return this.syncMeetings(connection); default: break; } diff --git a/packages/api/src/crm/note/services/attio/index.ts b/packages/api/src/crm/note/services/attio/index.ts index 03e637fd0..abad7c908 100644 --- a/packages/api/src/crm/note/services/attio/index.ts +++ b/packages/api/src/crm/note/services/attio/index.ts @@ -60,15 +60,7 @@ export class AttioService implements INoteService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'attio', - vertical: 'crm', - }, - }); + const { connection } = data; const baseURL = `${connection.account_url}/v2/notes`; diff --git a/packages/api/src/crm/note/services/close/index.ts b/packages/api/src/crm/note/services/close/index.ts index 8ac07982f..a14036559 100644 --- a/packages/api/src/crm/note/services/close/index.ts +++ b/packages/api/src/crm/note/services/close/index.ts @@ -60,15 +60,7 @@ export class CloseService implements INoteService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); + const { connection } = data; const baseURL = `${connection.account_url}/v1/activity/note`; diff --git a/packages/api/src/crm/note/services/hubspot/index.ts b/packages/api/src/crm/note/services/hubspot/index.ts index 641589e16..2f76a395e 100644 --- a/packages/api/src/crm/note/services/hubspot/index.ts +++ b/packages/api/src/crm/note/services/hubspot/index.ts @@ -75,15 +75,7 @@ export class HubspotService implements INoteService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); + const { connection, custom_properties } = data; const commonPropertyNames = Object.keys(commonNoteHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; diff --git a/packages/api/src/crm/note/services/microsoftdynamicssales/index.ts b/packages/api/src/crm/note/services/microsoftdynamicssales/index.ts index 475fba1e5..c2cc55740 100644 --- a/packages/api/src/crm/note/services/microsoftdynamicssales/index.ts +++ b/packages/api/src/crm/note/services/microsoftdynamicssales/index.ts @@ -8,102 +8,98 @@ import { INoteService } from '@crm/note/types'; import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; -import { MicrosoftdynamicssalesNoteInput, MicrosoftdynamicssalesNoteOutput } from './types'; +import { + MicrosoftdynamicssalesNoteInput, + MicrosoftdynamicssalesNoteOutput, +} from './types'; @Injectable() export class MicrosoftdynamicssalesService implements INoteService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - CrmObject.note.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, - ); - this.registry.registerService('microsoftdynamicssales', this); - } - - async addNote( - noteData: MicrosoftdynamicssalesNoteInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - const respToPost = await axios.post( - `${connection.account_url}/api/data/v9.2/annotations`, - JSON.stringify(noteData), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + CrmObject.note.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, + ); + this.registry.registerService('microsoftdynamicssales', this); + } - const postNoteId = respToPost.headers['location'].split("/").pop(); + async addNote( + noteData: MicrosoftdynamicssalesNoteInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'microsoftdynamicssales', + vertical: 'crm', + }, + }); + const respToPost = await axios.post( + `${connection.account_url}/api/data/v9.2/annotations`, + JSON.stringify(noteData), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/${postNoteId}` - , { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); + const postNoteId = respToPost.headers['location'].split('/').pop(); + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/${postNoteId}`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); - - return { - data: resp?.data, - message: 'Microsoftdynamicssales note created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + return { + data: resp?.data, + message: 'Microsoftdynamicssales note created', + statusCode: 201, + }; + } catch (error) { + throw error; } + } - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); + async sync( + data: SyncParam, + ): Promise> { + try { + const { connection } = data; - const baseURL = `${connection.account_url}/api/data/v9.2/annotations`; + const baseURL = `${connection.account_url}/api/data/v9.2/annotations`; - const resp = await axios.get(baseURL, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Synced microsoftdynamicssales notes !`); - return { - data: resp?.data?.value, - message: 'Microsoftdynamicssales notes retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + const resp = await axios.get(baseURL, { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }); + this.logger.log(`Synced microsoftdynamicssales notes !`); + return { + data: resp?.data?.value, + message: 'Microsoftdynamicssales notes retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/crm/note/services/pipedrive/index.ts b/packages/api/src/crm/note/services/pipedrive/index.ts index e9a9f7487..6439dc9fd 100644 --- a/packages/api/src/crm/note/services/pipedrive/index.ts +++ b/packages/api/src/crm/note/services/pipedrive/index.ts @@ -61,15 +61,8 @@ export class PipedriveService implements INoteService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); const resp = await axios.get(`${connection.account_url}/v1/notes`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/note/services/salesforce/index.ts b/packages/api/src/crm/note/services/salesforce/index.ts index 0789f00a5..2b010daf4 100644 --- a/packages/api/src/crm/note/services/salesforce/index.ts +++ b/packages/api/src/crm/note/services/salesforce/index.ts @@ -81,15 +81,7 @@ export class SalesforceService implements INoteService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties, pageSize, cursor } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'salesforce', - vertical: 'crm', - }, - }); + const { connection, custom_properties, pageSize, cursor } = data; const instanceUrl = connection.account_url; let pagingString = ''; diff --git a/packages/api/src/crm/note/services/zendesk/index.ts b/packages/api/src/crm/note/services/zendesk/index.ts index 593d49cc8..d5e7020b4 100644 --- a/packages/api/src/crm/note/services/zendesk/index.ts +++ b/packages/api/src/crm/note/services/zendesk/index.ts @@ -63,15 +63,8 @@ export class ZendeskService implements INoteService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'crm', - }, - }); const resp = await axios.get(`${connection.account_url}/v2/notes`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/note/services/zoho/index.ts b/packages/api/src/crm/note/services/zoho/index.ts index c3deb127f..ec1186e59 100644 --- a/packages/api/src/crm/note/services/zoho/index.ts +++ b/packages/api/src/crm/note/services/zoho/index.ts @@ -87,15 +87,8 @@ export class ZohoService implements INoteService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zoho', - vertical: 'crm', - }, - }); const fields = 'Note_Title,Note_Content,Owner,ParentId'; const resp = await axios.get( `${connection.account_url}/v5/Notes?fields=${fields}`, diff --git a/packages/api/src/crm/stage/services/close/index.ts b/packages/api/src/crm/stage/services/close/index.ts index 7b6696bf9..9a196e8a8 100644 --- a/packages/api/src/crm/stage/services/close/index.ts +++ b/packages/api/src/crm/stage/services/close/index.ts @@ -28,15 +28,7 @@ export class CloseService implements IStageService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, deal_id } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); + const { connection, deal_id } = data; const res = await this.prisma.crm_deals.findUnique({ where: { id_crm_deal: deal_id as string }, diff --git a/packages/api/src/crm/stage/services/hubspot/index.ts b/packages/api/src/crm/stage/services/hubspot/index.ts index 5187d8188..e0063b71c 100644 --- a/packages/api/src/crm/stage/services/hubspot/index.ts +++ b/packages/api/src/crm/stage/services/hubspot/index.ts @@ -27,15 +27,7 @@ export class HubspotService implements IStageService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); + const { connection } = data; // get all stages for all deals const url = 'https://api.hubapi.com/crm-pipelines/v1/pipelines/deals'; diff --git a/packages/api/src/crm/stage/services/pipedrive/index.ts b/packages/api/src/crm/stage/services/pipedrive/index.ts index 5fe58862e..815664972 100644 --- a/packages/api/src/crm/stage/services/pipedrive/index.ts +++ b/packages/api/src/crm/stage/services/pipedrive/index.ts @@ -27,15 +27,8 @@ export class PipedriveService implements IStageService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, deal_id } = data; + const { connection, deal_id } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); const res = await this.prisma.crm_deals.findUnique({ where: { id_crm_deal: deal_id as string }, }); diff --git a/packages/api/src/crm/stage/services/zendesk/index.ts b/packages/api/src/crm/stage/services/zendesk/index.ts index e6817dbd6..84295b5f2 100644 --- a/packages/api/src/crm/stage/services/zendesk/index.ts +++ b/packages/api/src/crm/stage/services/zendesk/index.ts @@ -26,15 +26,7 @@ export class ZendeskService implements IStageService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, deal_id } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'crm', - }, - }); + const { connection, deal_id } = data; const res = await this.prisma.crm_deals.findUnique({ where: { id_crm_deal: deal_id as string }, }); diff --git a/packages/api/src/crm/task/services/attio/index.ts b/packages/api/src/crm/task/services/attio/index.ts index c55541a40..7ebb3fcbe 100644 --- a/packages/api/src/crm/task/services/attio/index.ts +++ b/packages/api/src/crm/task/services/attio/index.ts @@ -81,15 +81,7 @@ export class AttioService implements ITaskService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'attio', - vertical: 'crm', - }, - }); + const { connection } = data; const baseURL = `${connection.account_url}/v2/tasks`; diff --git a/packages/api/src/crm/task/services/close/index.ts b/packages/api/src/crm/task/services/close/index.ts index e7d00af54..5600694fb 100644 --- a/packages/api/src/crm/task/services/close/index.ts +++ b/packages/api/src/crm/task/services/close/index.ts @@ -62,15 +62,7 @@ export class CloseService implements ITaskService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); + const { connection } = data; const baseURL = `${connection.account_url}/v1/task`; diff --git a/packages/api/src/crm/task/services/hubspot/index.ts b/packages/api/src/crm/task/services/hubspot/index.ts index 638d6c0f8..61858f021 100644 --- a/packages/api/src/crm/task/services/hubspot/index.ts +++ b/packages/api/src/crm/task/services/hubspot/index.ts @@ -74,15 +74,7 @@ export class HubspotService implements ITaskService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); + const { connection, custom_properties } = data; const commonPropertyNames = Object.keys(commonTaskHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; diff --git a/packages/api/src/crm/task/services/microsoftdynamicssales/index.ts b/packages/api/src/crm/task/services/microsoftdynamicssales/index.ts index 3888854b6..4b52be155 100644 --- a/packages/api/src/crm/task/services/microsoftdynamicssales/index.ts +++ b/packages/api/src/crm/task/services/microsoftdynamicssales/index.ts @@ -8,101 +8,98 @@ import { ITaskService } from '@crm/task/types'; import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; -import { MicrosoftdynamicssalesTaskInput, MicrosoftdynamicssalesTaskOutput } from './types'; +import { + MicrosoftdynamicssalesTaskInput, + MicrosoftdynamicssalesTaskOutput, +} from './types'; @Injectable() export class MicrosoftdynamicssalesService implements ITaskService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - CrmObject.task.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, - ); - this.registry.registerService('microsoftdynamicssales', this); - } - - async addTask( - taskData: MicrosoftdynamicssalesTaskInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - const respToPost = await axios.post( - `${connection.account_url}/api/data/v9.2/tasks`, - JSON.stringify(taskData), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + CrmObject.task.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, + ); + this.registry.registerService('microsoftdynamicssales', this); + } - const postTaskId = respToPost.headers['location'].split("/").pop(); + async addTask( + taskData: MicrosoftdynamicssalesTaskInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'microsoftdynamicssales', + vertical: 'crm', + }, + }); + const respToPost = await axios.post( + `${connection.account_url}/api/data/v9.2/tasks`, + JSON.stringify(taskData), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); - const resp = await axios.get( - `${connection.account_url}/api/data/v9.2/${postTaskId}`, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); + const postTaskId = respToPost.headers['location'].split('/').pop(); + const resp = await axios.get( + `${connection.account_url}/api/data/v9.2/${postTaskId}`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); - - return { - data: resp?.data, - message: 'Microsoftdynamicssales task created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + return { + data: resp?.data, + message: 'Microsoftdynamicssales task created', + statusCode: 201, + }; + } catch (error) { + throw error; } + } - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); + async sync( + data: SyncParam, + ): Promise> { + try { + const { connection } = data; - const baseURL = `${connection.account_url}/api/data/v9.2/tasks`; + const baseURL = `${connection.account_url}/api/data/v9.2/tasks`; - const resp = await axios.get(baseURL, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Synced microsoftdynamicssales tasks !`); - return { - data: resp?.data?.value, - message: 'Microsoftdynamicssales tasks retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + const resp = await axios.get(baseURL, { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }); + this.logger.log(`Synced microsoftdynamicssales tasks !`); + return { + data: resp?.data?.value, + message: 'Microsoftdynamicssales tasks retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/crm/task/services/pipedrive/index.ts b/packages/api/src/crm/task/services/pipedrive/index.ts index 56e953964..c52fc7240 100644 --- a/packages/api/src/crm/task/services/pipedrive/index.ts +++ b/packages/api/src/crm/task/services/pipedrive/index.ts @@ -62,15 +62,8 @@ export class PipedriveService implements ITaskService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); const resp = await axios.get( `${connection.account_url}/v1/activities?type=task`, { diff --git a/packages/api/src/crm/task/services/salesforce/index.ts b/packages/api/src/crm/task/services/salesforce/index.ts index 4d84bd650..ad978fd02 100644 --- a/packages/api/src/crm/task/services/salesforce/index.ts +++ b/packages/api/src/crm/task/services/salesforce/index.ts @@ -81,20 +81,12 @@ export class SalesforceService implements ITaskService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties, pageSize, cursor } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'salesforce', - vertical: 'crm', - }, - }); + const { connection, custom_properties, pageSize, cursor } = data; const instanceUrl = connection.account_url; - let pagingString = `${pageSize ? `ORDER BY Id DESC LIMIT ${pageSize} ` : ''}${ - cursor ? `OFFSET ${cursor}` : '' - }`; + let pagingString = `${ + pageSize ? `ORDER BY Id DESC LIMIT ${pageSize} ` : '' + }${cursor ? `OFFSET ${cursor}` : ''}`; if (!pageSize && !cursor) { pagingString = 'LIMIT 200'; } @@ -106,7 +98,9 @@ export class SalesforceService implements ITaskService { const query = `SELECT ${fields} FROM Task ${pagingString}`; const resp = await axios.get( - `${instanceUrl}/services/data/v56.0/query/?q=${encodeURIComponent(query)}`, + `${instanceUrl}/services/data/v56.0/query/?q=${encodeURIComponent( + query, + )}`, { headers: { Authorization: `Bearer ${this.cryptoService.decrypt( @@ -127,4 +121,4 @@ export class SalesforceService implements ITaskService { throw error; } } -} \ No newline at end of file +} diff --git a/packages/api/src/crm/task/services/zendesk/index.ts b/packages/api/src/crm/task/services/zendesk/index.ts index 7194ae7b2..6ac396bd8 100644 --- a/packages/api/src/crm/task/services/zendesk/index.ts +++ b/packages/api/src/crm/task/services/zendesk/index.ts @@ -66,15 +66,8 @@ export class ZendeskService implements ITaskService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'crm', - }, - }); const resp = await axios.get(`${connection.account_url}/v2/tasks`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/task/services/zoho/index.ts b/packages/api/src/crm/task/services/zoho/index.ts index 06e54795c..baa935e90 100644 --- a/packages/api/src/crm/task/services/zoho/index.ts +++ b/packages/api/src/crm/task/services/zoho/index.ts @@ -26,15 +26,8 @@ export class ZohoService implements ITaskService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zoho', - vertical: 'crm', - }, - }); const fields = 'Status,Owner,Description,Due_Date,Priority,Closed_Time,Subject,What_Id'; const resp = await axios.get( diff --git a/packages/api/src/crm/user/services/attio/index.ts b/packages/api/src/crm/user/services/attio/index.ts index 5dca4f0e0..14bbd600d 100644 --- a/packages/api/src/crm/user/services/attio/index.ts +++ b/packages/api/src/crm/user/services/attio/index.ts @@ -26,15 +26,7 @@ export class AttioService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'attio', - vertical: 'crm', - }, - }); + const { connection } = data; const baseURL = `${connection.account_url}/v2/workspace_members`; const resp = await axios.get(baseURL, { diff --git a/packages/api/src/crm/user/services/close/index.ts b/packages/api/src/crm/user/services/close/index.ts index c5b6b9d9e..d46f9e647 100644 --- a/packages/api/src/crm/user/services/close/index.ts +++ b/packages/api/src/crm/user/services/close/index.ts @@ -27,15 +27,7 @@ export class CloseService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'close', - vertical: 'crm', - }, - }); + const { connection } = data; const baseURL = `${connection.account_url}/v1/user`; const resp = await axios.get(baseURL, { diff --git a/packages/api/src/crm/user/services/hubspot/index.ts b/packages/api/src/crm/user/services/hubspot/index.ts index d09ee4072..cb1046a86 100644 --- a/packages/api/src/crm/user/services/hubspot/index.ts +++ b/packages/api/src/crm/user/services/hubspot/index.ts @@ -26,15 +26,9 @@ export class HubspotService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties } = data; + const { connection, custom_properties } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'hubspot', - vertical: 'crm', - }, - }); + const commonPropertyNames = Object.keys(commonUserHubspotProperties); const allProperties = [...commonPropertyNames, ...custom_properties]; diff --git a/packages/api/src/crm/user/services/microsoftdynamicssales/index.ts b/packages/api/src/crm/user/services/microsoftdynamicssales/index.ts index 83b1170b6..04aa71031 100644 --- a/packages/api/src/crm/user/services/microsoftdynamicssales/index.ts +++ b/packages/api/src/crm/user/services/microsoftdynamicssales/index.ts @@ -12,56 +12,51 @@ import { MicrosoftdynamicssalesUserOutput } from './types'; @Injectable() export class MicrosoftdynamicssalesService implements IUserService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - CrmObject.user.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, - ); - this.registry.registerService('microsoftdynamicssales', this); - } - - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'microsoftdynamicssales', - vertical: 'crm', - }, - }); - - this.logger.log("==========="); - this.logger.log(this.cryptoService.decrypt( - connection.access_token, - )); - this.logger.log("==========="); - - - const baseURL = `${connection.account_url}/api/data/v9.2/systemusers`; - const resp = await axios.get(baseURL, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - - this.logger.log(`Synced microsoftdynamicssales users ! : ${JSON.stringify(resp.data.value)}`); - - return { - data: resp.data.value, - message: 'Microsoftdynamicssales users retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + CrmObject.user.toUpperCase() + ':' + MicrosoftdynamicssalesService.name, + ); + this.registry.registerService('microsoftdynamicssales', this); + } + + async sync( + data: SyncParam, + ): Promise> { + try { + const { connection } = data; + + this.logger.log('==========='); + this.logger.log(this.cryptoService.decrypt(connection.access_token)); + this.logger.log('==========='); + + const baseURL = `${connection.account_url}/api/data/v9.2/systemusers`; + const resp = await axios.get(baseURL, { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }); + + this.logger.log( + `Synced microsoftdynamicssales users ! : ${JSON.stringify( + resp.data.value, + )}`, + ); + + return { + data: resp.data.value, + message: 'Microsoftdynamicssales users retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/crm/user/services/pipedrive/index.ts b/packages/api/src/crm/user/services/pipedrive/index.ts index dd06a1708..b79149a39 100644 --- a/packages/api/src/crm/user/services/pipedrive/index.ts +++ b/packages/api/src/crm/user/services/pipedrive/index.ts @@ -27,15 +27,8 @@ export class PipedriveService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'pipedrive', - vertical: 'crm', - }, - }); const resp = await axios.get(`${connection.account_url}/v1/users`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/user/services/salesforce/index.ts b/packages/api/src/crm/user/services/salesforce/index.ts index 22badde90..9222a1a6a 100644 --- a/packages/api/src/crm/user/services/salesforce/index.ts +++ b/packages/api/src/crm/user/services/salesforce/index.ts @@ -26,20 +26,12 @@ export class SalesforceService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, custom_properties, pageSize, cursor } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'salesforce', - vertical: 'crm', - }, - }); + const { connection, custom_properties, pageSize, cursor } = data; const instanceUrl = connection.account_url; - let pagingString = `${pageSize ? `ORDER BY Id DESC LIMIT ${pageSize} ` : ''}${ - cursor ? `OFFSET ${cursor}` : '' - }`; + let pagingString = `${ + pageSize ? `ORDER BY Id DESC LIMIT ${pageSize} ` : '' + }${cursor ? `OFFSET ${cursor}` : ''}`; if (!pageSize && !cursor) { pagingString = 'LIMIT 200'; } @@ -51,7 +43,9 @@ export class SalesforceService implements IUserService { const query = `SELECT ${fields} FROM User ${pagingString}`; const resp = await axios.get( - `${instanceUrl}/services/data/v56.0/query/?q=${encodeURIComponent(query)}`, + `${instanceUrl}/services/data/v56.0/query/?q=${encodeURIComponent( + query, + )}`, { headers: { Authorization: `Bearer ${this.cryptoService.decrypt( @@ -72,4 +66,4 @@ export class SalesforceService implements IUserService { throw error; } } -} \ No newline at end of file +} diff --git a/packages/api/src/crm/user/services/zendesk/index.ts b/packages/api/src/crm/user/services/zendesk/index.ts index 322bee511..57a844dce 100644 --- a/packages/api/src/crm/user/services/zendesk/index.ts +++ b/packages/api/src/crm/user/services/zendesk/index.ts @@ -26,15 +26,8 @@ export class ZendeskService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'crm', - }, - }); const resp = await axios.get(`${connection.account_url}/v2/users`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/crm/user/services/zoho/index.ts b/packages/api/src/crm/user/services/zoho/index.ts index e05980345..ab0659536 100644 --- a/packages/api/src/crm/user/services/zoho/index.ts +++ b/packages/api/src/crm/user/services/zoho/index.ts @@ -27,15 +27,8 @@ export class ZohoService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zoho', - vertical: 'crm', - }, - }); const resp = await axios.get( `${connection.account_url}/v5/users?type=AllUsers`, { diff --git a/packages/api/src/ecommerce/customer/services/shopify/index.ts b/packages/api/src/ecommerce/customer/services/shopify/index.ts index 9a323c8e1..6d7020730 100644 --- a/packages/api/src/ecommerce/customer/services/shopify/index.ts +++ b/packages/api/src/ecommerce/customer/services/shopify/index.ts @@ -26,15 +26,8 @@ export class ShopifyService implements ICustomerService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'shopify', - vertical: 'ecommerce', - }, - }); const resp = await axios.get( `${connection.account_url}/admin/api/2024-07/customers.json`, { diff --git a/packages/api/src/ecommerce/customer/services/webflow/index.ts b/packages/api/src/ecommerce/customer/services/webflow/index.ts index 54c747341..5abf766b0 100644 --- a/packages/api/src/ecommerce/customer/services/webflow/index.ts +++ b/packages/api/src/ecommerce/customer/services/webflow/index.ts @@ -26,15 +26,7 @@ export class WebflowService implements ICustomerService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'webflow', - vertical: 'ecommerce', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/users`, { headers: { diff --git a/packages/api/src/ecommerce/customer/services/woocommerce/index.ts b/packages/api/src/ecommerce/customer/services/woocommerce/index.ts index 2ccd22eac..cbff76321 100644 --- a/packages/api/src/ecommerce/customer/services/woocommerce/index.ts +++ b/packages/api/src/ecommerce/customer/services/woocommerce/index.ts @@ -28,15 +28,8 @@ export class WoocommerceService implements ICustomerService { data: SyncParam, ): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'woocommerce', - vertical: 'ecommerce', - }, - }); const decryptedData = JSON.parse( this.cryptoService.decrypt(connection.access_token), ); diff --git a/packages/api/src/ecommerce/fulfillment/services/shopify/index.ts b/packages/api/src/ecommerce/fulfillment/services/shopify/index.ts index e85d4e6fd..5093b7850 100644 --- a/packages/api/src/ecommerce/fulfillment/services/shopify/index.ts +++ b/packages/api/src/ecommerce/fulfillment/services/shopify/index.ts @@ -30,15 +30,8 @@ export class ShopifyService implements IFulfillmentService { data: SyncParam, ): Promise> { try { - const { linkedUserId, id_order } = data; + const { connection, id_order } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'shopify', - vertical: 'ecommerce', - }, - }); //retrieve ticket remote id so we can retrieve the comments in the original software const order = await this.prisma.ecom_orders.findUnique({ where: { diff --git a/packages/api/src/ecommerce/fulfillmentorders/services/shopify/index.ts b/packages/api/src/ecommerce/fulfillmentorders/services/shopify/index.ts index e736358cc..4d465d2e5 100644 --- a/packages/api/src/ecommerce/fulfillmentorders/services/shopify/index.ts +++ b/packages/api/src/ecommerce/fulfillmentorders/services/shopify/index.ts @@ -32,15 +32,8 @@ export class ShopifyService implements IFulfillmentOrdersService { data: SyncParam, ): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'shopify', - vertical: 'ecommerce', - }, - }); const resp = await axios.post( `${connection.account_url}/departement.list`, { diff --git a/packages/api/src/ecommerce/order/services/amazon/index.ts b/packages/api/src/ecommerce/order/services/amazon/index.ts index 4b902a81c..0b43799ac 100644 --- a/packages/api/src/ecommerce/order/services/amazon/index.ts +++ b/packages/api/src/ecommerce/order/services/amazon/index.ts @@ -81,15 +81,8 @@ export class AmazonService implements IOrderService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'amazon', - vertical: 'ecommerce', - }, - }); const specificMarketplaceIds = marketplaces.map( (marketplace) => marketplace.marketplaceId, ); diff --git a/packages/api/src/ecommerce/order/services/shopify/index.ts b/packages/api/src/ecommerce/order/services/shopify/index.ts index b70979d35..21ac75720 100644 --- a/packages/api/src/ecommerce/order/services/shopify/index.ts +++ b/packages/api/src/ecommerce/order/services/shopify/index.ts @@ -63,15 +63,8 @@ export class ShopifyService implements IOrderService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'shopify', - vertical: 'ecommerce', - }, - }); const resp = await axios.get( `${connection.account_url}/admin/api/2024-07/orders.json`, { diff --git a/packages/api/src/ecommerce/order/services/squarespace/index.ts b/packages/api/src/ecommerce/order/services/squarespace/index.ts index 38dfc40d9..0450b4b76 100644 --- a/packages/api/src/ecommerce/order/services/squarespace/index.ts +++ b/packages/api/src/ecommerce/order/services/squarespace/index.ts @@ -27,15 +27,8 @@ export class SquarespaceService implements IOrderService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'squarespace', - vertical: 'ecommerce', - }, - }); const resp = await axios.get( `${connection.account_url}/1.0/commerce/orders`, { diff --git a/packages/api/src/ecommerce/order/services/webflow/index.ts b/packages/api/src/ecommerce/order/services/webflow/index.ts index b3d1c5ca3..c1db869ed 100644 --- a/packages/api/src/ecommerce/order/services/webflow/index.ts +++ b/packages/api/src/ecommerce/order/services/webflow/index.ts @@ -25,15 +25,8 @@ export class WebflowService implements IOrderService { } async sync(data: SyncParam): Promise> { + const { connection } = data; try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: data.linkedUserId, - provider_slug: 'webflow', - vertical: 'ecommerce', - }, - }); - // ref: https://docs.developers.webflow.com/data/reference/list-orders const resp = await axios.get(`${connection.account_url}/orders`, { headers: { diff --git a/packages/api/src/ecommerce/order/services/woocommerce/index.ts b/packages/api/src/ecommerce/order/services/woocommerce/index.ts index 82fb6ee67..c43679e4c 100644 --- a/packages/api/src/ecommerce/order/services/woocommerce/index.ts +++ b/packages/api/src/ecommerce/order/services/woocommerce/index.ts @@ -69,15 +69,8 @@ export class WoocommerceService implements IOrderService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'woocommerce', - vertical: 'ecommerce', - }, - }); const decryptedData = JSON.parse( this.cryptoService.decrypt(connection.access_token), ); diff --git a/packages/api/src/ecommerce/product/services/shopify/index.ts b/packages/api/src/ecommerce/product/services/shopify/index.ts index aee4aa1a9..7550e198a 100644 --- a/packages/api/src/ecommerce/product/services/shopify/index.ts +++ b/packages/api/src/ecommerce/product/services/shopify/index.ts @@ -65,15 +65,8 @@ export class ShopifyService implements IProductService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'shopify', - vertical: 'ecommerce', - }, - }); const resp = await axios.get( `${connection.account_url}/admin/api/2024-07/products.json`, { diff --git a/packages/api/src/ecommerce/product/services/squarespace/index.ts b/packages/api/src/ecommerce/product/services/squarespace/index.ts index 39ff44d2f..ad1b13da0 100644 --- a/packages/api/src/ecommerce/product/services/squarespace/index.ts +++ b/packages/api/src/ecommerce/product/services/squarespace/index.ts @@ -30,15 +30,8 @@ export class SquarespaceService implements IProductService { data: SyncParam, ): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'squarespace', - vertical: 'ecommerce', - }, - }); const resp = await axios.get( `${connection.account_url}/1.1/commerce/products?type=PHYSICAL,DIGITAL`, { diff --git a/packages/api/src/ecommerce/product/services/webflow/index.ts b/packages/api/src/ecommerce/product/services/webflow/index.ts index 92ebdb1b4..0b453bd4e 100644 --- a/packages/api/src/ecommerce/product/services/webflow/index.ts +++ b/packages/api/src/ecommerce/product/services/webflow/index.ts @@ -64,15 +64,8 @@ export class WebflowService implements IProductService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'webflow', - vertical: 'ecommerce', - }, - }); const resp = await axios.get( // https://api.webflow.com/v2/sites/{site_id}/products `${connection.account_url}/products`, diff --git a/packages/api/src/ecommerce/product/services/woocommerce/index.ts b/packages/api/src/ecommerce/product/services/woocommerce/index.ts index 575fff649..6a97f9640 100644 --- a/packages/api/src/ecommerce/product/services/woocommerce/index.ts +++ b/packages/api/src/ecommerce/product/services/woocommerce/index.ts @@ -72,15 +72,8 @@ export class WoocommerceService implements IProductService { data: SyncParam, ): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'woocommerce', - vertical: 'ecommerce', - }, - }); const decryptedData = JSON.parse( this.cryptoService.decrypt(connection.access_token), ); diff --git a/packages/api/src/filestorage/drive/services/googledrive/index.ts b/packages/api/src/filestorage/drive/services/googledrive/index.ts index 945037f97..569b7f923 100644 --- a/packages/api/src/filestorage/drive/services/googledrive/index.ts +++ b/packages/api/src/filestorage/drive/services/googledrive/index.ts @@ -11,6 +11,7 @@ import { OAuth2Client } from 'google-auth-library'; import { google } from 'googleapis'; import { ServiceRegistry } from '../registry.service'; import { GoogleDriveDriveOutput } from './types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class GoogleDriveService implements IDriveService { @@ -26,15 +27,7 @@ export class GoogleDriveService implements IDriveService { this.registry.registerService('googledrive', this); } - private async getGoogleClient(linkedUserId: string): Promise { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'googledrive', - vertical: 'filestorage', - }, - }); - + private async getGoogleClient(connection: Connection): Promise { if (!connection) { throw new Error('Connection not found'); } @@ -53,7 +46,14 @@ export class GoogleDriveService implements IDriveService { linkedUserId: string, ): Promise> { try { - const oauth2Client = await this.getGoogleClient(linkedUserId); + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'googledrive', + vertical: 'filestorage', + }, + }); + const oauth2Client = await this.getGoogleClient(connection); const drive = google.drive({ version: 'v3', auth: oauth2Client }); const response = await drive.drives.create({ @@ -81,8 +81,8 @@ export class GoogleDriveService implements IDriveService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const oauth2Client = await this.getGoogleClient(linkedUserId); + const { connection } = data; + const oauth2Client = await this.getGoogleClient(connection); const drive = google.drive({ version: 'v3', auth: oauth2Client }); const response = await drive.drives.list({ diff --git a/packages/api/src/filestorage/drive/services/onedrive/index.ts b/packages/api/src/filestorage/drive/services/onedrive/index.ts index 4d6229441..55677d06e 100644 --- a/packages/api/src/filestorage/drive/services/onedrive/index.ts +++ b/packages/api/src/filestorage/drive/services/onedrive/index.ts @@ -36,15 +36,7 @@ export class OnedriveService implements IDriveService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'onedrive', - vertical: 'filestorage', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/v1.0/drives`, { headers: { diff --git a/packages/api/src/filestorage/drive/services/sharepoint/index.ts b/packages/api/src/filestorage/drive/services/sharepoint/index.ts index 9fece13b1..24845f826 100644 --- a/packages/api/src/filestorage/drive/services/sharepoint/index.ts +++ b/packages/api/src/filestorage/drive/services/sharepoint/index.ts @@ -36,15 +36,7 @@ export class SharepointService implements IDriveService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sharepoint', - vertical: 'filestorage', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/drives`, { headers: { diff --git a/packages/api/src/filestorage/file/services/box/index.ts b/packages/api/src/filestorage/file/services/box/index.ts index 4576b66a1..5e0865e08 100644 --- a/packages/api/src/filestorage/file/services/box/index.ts +++ b/packages/api/src/filestorage/file/services/box/index.ts @@ -26,17 +26,9 @@ export class BoxService implements IFileService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_folder } = data; + const { connection, id_folder } = data; if (!id_folder) return; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'box', - vertical: 'filestorage', - }, - }); - const folder = await this.prisma.fs_folders.findUnique({ where: { id_fs_folder: id_folder as string, diff --git a/packages/api/src/filestorage/file/services/dropbox/index.ts b/packages/api/src/filestorage/file/services/dropbox/index.ts index 81152fc50..8a29cab81 100644 --- a/packages/api/src/filestorage/file/services/dropbox/index.ts +++ b/packages/api/src/filestorage/file/services/dropbox/index.ts @@ -68,17 +68,9 @@ export class DropboxService implements IFileService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_folder } = data; + const { connection, id_folder } = data; if (!id_folder) return; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'dropbox', - vertical: 'filestorage', - }, - }); - const folder = await this.prisma.fs_folders.findUnique({ where: { id_fs_folder: id_folder as string, diff --git a/packages/api/src/filestorage/file/services/googledrive/index.ts b/packages/api/src/filestorage/file/services/googledrive/index.ts index 6fbf1c0d3..e9c9a0221 100644 --- a/packages/api/src/filestorage/file/services/googledrive/index.ts +++ b/packages/api/src/filestorage/file/services/googledrive/index.ts @@ -28,15 +28,7 @@ export class GoogleDriveService implements IFileService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_folder } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'googledrive', - vertical: 'filestorage', - }, - }); + const { connection, id_folder } = data; if (!connection) return; diff --git a/packages/api/src/filestorage/file/services/onedrive/index.ts b/packages/api/src/filestorage/file/services/onedrive/index.ts index 1e9992155..2e7a483b7 100644 --- a/packages/api/src/filestorage/file/services/onedrive/index.ts +++ b/packages/api/src/filestorage/file/services/onedrive/index.ts @@ -28,15 +28,7 @@ export class OnedriveService implements IFileService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_folder } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'onedrive', - vertical: 'filestorage', - }, - }); + const { connection, id_folder } = data; const foldersToSync = ['root']; if (id_folder) { diff --git a/packages/api/src/filestorage/file/services/sharepoint/index.ts b/packages/api/src/filestorage/file/services/sharepoint/index.ts index cf96e4f82..b539ff8d5 100644 --- a/packages/api/src/filestorage/file/services/sharepoint/index.ts +++ b/packages/api/src/filestorage/file/services/sharepoint/index.ts @@ -9,6 +9,7 @@ import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { SharepointFileOutput } from './types'; +import { FieldMappingService } from '@@core/field-mapping/field-mapping.service'; @Injectable() export class SharepointService implements IFileService { @@ -17,6 +18,7 @@ export class SharepointService implements IFileService { private logger: LoggerService, private cryptoService: EncryptionService, private registry: ServiceRegistry, + private fieldMappingService: FieldMappingService, ) { this.logger.setContext( `${FileStorageObject.file.toUpperCase()}:${SharepointService.name}`, @@ -26,15 +28,7 @@ export class SharepointService implements IFileService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_folder } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sharepoint', - vertical: 'filestorage', - }, - }); + const { connection, id_folder } = data; const foldersToSync = ['root']; if (id_folder) { @@ -51,7 +45,7 @@ export class SharepointService implements IFileService { const allFiles: SharepointFileOutput[] = []; for (const folderId of foldersToSync) { - const files = await this.syncFolder(connection, folderId); + const files = await this.syncFolder(connection, folderId, linkedUserId); allFiles.push(...files); } @@ -75,7 +69,33 @@ export class SharepointService implements IFileService { private async syncFolder( connection: any, folderId: string, + linkedUserId: string, ): Promise { + const customFields = await this.fieldMappingService.getCustomFieldMappings( + 'sharepoint', + linkedUserId, + 'filestorage.file', + ); + + const selectFields = [ + 'id', + 'name', + 'webUrl', + 'createdDateTime', + 'lastModifiedDateTime', + 'size', + 'file', + 'folder', + 'permissions', + '@microsoft.graph.downloadUrl', + ]; + + if (customFields) { + customFields.forEach((field) => { + selectFields.push(`fields/${field.remote_id}`); + }); + } + const resp = await axios.get( `${connection.account_url}/drive/items/${folderId}/children`, { @@ -85,11 +105,15 @@ export class SharepointService implements IFileService { connection.access_token, )}`, }, + params: { + $select: selectFields.join(','), + $expand: 'fields', + }, }, ); const files: SharepointFileOutput[] = resp.data.value.filter( - (elem) => !elem.folder, // files don't have a folder property + (elem) => !elem.folder, ); // Add permissions (shared link is also included in permissions in SharePoint) diff --git a/packages/api/src/filestorage/file/services/sharepoint/mappers.ts b/packages/api/src/filestorage/file/services/sharepoint/mappers.ts index 7fd0f227b..37b777f41 100644 --- a/packages/api/src/filestorage/file/services/sharepoint/mappers.ts +++ b/packages/api/src/filestorage/file/services/sharepoint/mappers.ts @@ -84,7 +84,9 @@ export class SharepointFileMapper implements IFileMapper { const field_mappings: { [key: string]: any } = {}; if (customFieldMappings) { for (const mapping of customFieldMappings) { - field_mappings[mapping.slug] = file[mapping.remote_id]; + field_mappings[mapping.slug] = file.fields + ? file.fields[mapping.remote_id] + : null; } } diff --git a/packages/api/src/filestorage/file/services/sharepoint/types.ts b/packages/api/src/filestorage/file/services/sharepoint/types.ts index 32c34810a..7a9b4379d 100644 --- a/packages/api/src/filestorage/file/services/sharepoint/types.ts +++ b/packages/api/src/filestorage/file/services/sharepoint/types.ts @@ -57,6 +57,8 @@ export interface SharepointFileOutput { readonly video?: Video; /** WebDAV compatible URL for the item. */ readonly webDavUrl?: string; + /** Additional fields */ + fields?: { [key: string]: any }; } /** diff --git a/packages/api/src/filestorage/folder/services/box/index.ts b/packages/api/src/filestorage/folder/services/box/index.ts index f2532b71c..ee22d3710 100644 --- a/packages/api/src/filestorage/folder/services/box/index.ts +++ b/packages/api/src/filestorage/folder/services/box/index.ts @@ -13,6 +13,7 @@ import { SyncParam } from '@@core/utils/types/interface'; import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; import { BoxFileOutput } from '@filestorage/file/services/box/types'; import { UnifiedFilestorageFileOutput } from '@filestorage/file/types/model.unified'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class BoxService implements IFolderService { @@ -66,16 +67,9 @@ export class BoxService implements IFolderService { async recursiveGetBoxFolders( remote_folder_id: string, - linkedUserId: string, + connection: Connection, ): Promise { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'box', - vertical: 'filestorage', - }, - }); const resp = await axios.get( `${connection.account_url}/2.0/folders/${remote_folder_id}/items`, { @@ -89,7 +83,10 @@ export class BoxService implements IFolderService { ); const folders = resp.data.entries.filter((elem) => elem.type == 'folder'); const files = resp.data.entries.filter((elem) => elem.type == 'file'); - await this.ingestService.ingestData( + await this.ingestService.ingestData< + UnifiedFilestorageFileOutput, + BoxFileOutput + >( files, 'box', connection.id_connection, @@ -102,7 +99,7 @@ export class BoxService implements IFolderService { // Recursively get subfolders const subFolders = await this.recursiveGetBoxFolders( folder.id, - linkedUserId, + connection, ); results = results.concat(subFolders); } @@ -114,9 +111,9 @@ export class BoxService implements IFolderService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; // to sync all folders we start from root folder ("0") and recurse through it - const results = await this.recursiveGetBoxFolders('0', linkedUserId); + const results = await this.recursiveGetBoxFolders('0', connection); this.logger.log(`Synced box folders !`); return { diff --git a/packages/api/src/filestorage/folder/services/dropbox/index.ts b/packages/api/src/filestorage/folder/services/dropbox/index.ts index a3e60dc70..e77079ca5 100644 --- a/packages/api/src/filestorage/folder/services/dropbox/index.ts +++ b/packages/api/src/filestorage/folder/services/dropbox/index.ts @@ -103,15 +103,7 @@ export class DropboxService implements IFolderService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'dropbox', - vertical: 'filestorage', - }, - }); + const { connection } = data; const results = await this.getAllFolders(connection); this.logger.log(`Synced dropbox folders !`); diff --git a/packages/api/src/filestorage/folder/services/googledrive/index.ts b/packages/api/src/filestorage/folder/services/googledrive/index.ts index a029f1047..7dd0887ed 100644 --- a/packages/api/src/filestorage/folder/services/googledrive/index.ts +++ b/packages/api/src/filestorage/folder/services/googledrive/index.ts @@ -86,15 +86,7 @@ export class GoogleDriveFolderService implements IFolderService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'googledrive', - vertical: 'filestorage', - }, - }); + const { connection } = data; if (!connection) { return { diff --git a/packages/api/src/filestorage/folder/services/onedrive/index.ts b/packages/api/src/filestorage/folder/services/onedrive/index.ts index f02db9f95..e44832744 100644 --- a/packages/api/src/filestorage/folder/services/onedrive/index.ts +++ b/packages/api/src/filestorage/folder/services/onedrive/index.ts @@ -13,6 +13,7 @@ import { SyncParam } from '@@core/utils/types/interface'; import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; import { UnifiedFilestorageFileOutput } from '@filestorage/file/types/model.unified'; import { OnedriveFileOutput } from '@filestorage/file/services/onedrive/types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class OnedriveService implements IFolderService { @@ -72,17 +73,9 @@ export class OnedriveService implements IFolderService { async iterativeGetOnedriveFolders( remote_folder_id: string, - linkedUserId: string, + connection: Connection, ): Promise { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'onedrive', - vertical: 'filestorage', - }, - }); - let result = [], depth = 0, batch = [remote_folder_id]; @@ -163,11 +156,11 @@ export class OnedriveService implements IFolderService { async sync(data: SyncParam): Promise> { try { this.logger.log('Syncing onedrive folders'); - const { linkedUserId } = data; + const { connection } = data; const folders = await this.iterativeGetOnedriveFolders( 'root', - linkedUserId, + connection, ); this.logger.log(`${folders.length} onedrive folders found`); diff --git a/packages/api/src/filestorage/folder/services/sharepoint/index.ts b/packages/api/src/filestorage/folder/services/sharepoint/index.ts index c2ee70a7b..a0e9f0b21 100644 --- a/packages/api/src/filestorage/folder/services/sharepoint/index.ts +++ b/packages/api/src/filestorage/folder/services/sharepoint/index.ts @@ -10,6 +10,7 @@ import { Injectable } from '@nestjs/common'; import axios from 'axios'; import { ServiceRegistry } from '../registry.service'; import { SharepointFolderInput, SharepointFolderOutput } from './types'; +import { Connection } from '@@core/connections/@utils/types'; @Injectable() export class SharepointService implements IFolderService { constructor( @@ -69,17 +70,9 @@ export class SharepointService implements IFolderService { async iterativeGetSharepointFolders( remote_folder_id: string, - linkedUserId: string, + connection: Connection, ): Promise { try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sharepoint', - vertical: 'filestorage', - }, - }); - let result = [], depth = 0, batch = [remote_folder_id]; @@ -161,11 +154,11 @@ export class SharepointService implements IFolderService { async sync(data: SyncParam): Promise> { try { this.logger.log('Syncing sharepoint folders'); - const { linkedUserId } = data; + const { connection } = data; const folders = await this.iterativeGetSharepointFolders( 'root', - linkedUserId, + connection, ); this.logger.log(`${folders.length} sharepoint folders found`); diff --git a/packages/api/src/filestorage/group/services/box/index.ts b/packages/api/src/filestorage/group/services/box/index.ts index bcac63da6..97feeb509 100644 --- a/packages/api/src/filestorage/group/services/box/index.ts +++ b/packages/api/src/filestorage/group/services/box/index.ts @@ -26,14 +26,8 @@ export class BoxService implements IGroupService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'box', - vertical: 'filestorage', - }, - }); + const { connection } = data; + const resp = await axios.get(`${connection.account_url}/2.0/groups`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/filestorage/group/services/dropbox/index.ts b/packages/api/src/filestorage/group/services/dropbox/index.ts index 4ebc75247..122a226aa 100644 --- a/packages/api/src/filestorage/group/services/dropbox/index.ts +++ b/packages/api/src/filestorage/group/services/dropbox/index.ts @@ -26,14 +26,7 @@ export class DropboxService implements IGroupService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'dropbox', - vertical: 'filestorage', - }, - }); + const { connection } = data; // ref: https://www.dropbox.com/developers/documentation/http/teams#team-groups-list const resp = await axios.post( diff --git a/packages/api/src/filestorage/group/services/onedrive/index.ts b/packages/api/src/filestorage/group/services/onedrive/index.ts index fbd0e58df..6d809a425 100644 --- a/packages/api/src/filestorage/group/services/onedrive/index.ts +++ b/packages/api/src/filestorage/group/services/onedrive/index.ts @@ -26,14 +26,8 @@ export class OnedriveService implements IGroupService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'onedrive', - vertical: 'filestorage', - }, - }); + const { connection } = data; + const resp = await axios.get(`${connection.account_url}/v1.0/groups`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/filestorage/group/services/sharepoint/index.ts b/packages/api/src/filestorage/group/services/sharepoint/index.ts index f839eccdf..8cbbe5f6e 100644 --- a/packages/api/src/filestorage/group/services/sharepoint/index.ts +++ b/packages/api/src/filestorage/group/services/sharepoint/index.ts @@ -26,14 +26,8 @@ export class SharepointService implements IGroupService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sharepoint', - vertical: 'filestorage', - }, - }); + const { connection } = data; + // remove /sites/site_id from account_url const url = connection.account_url.replace(/\/sites\/.+$/, ''); diff --git a/packages/api/src/filestorage/permission/services/onedrive/index.ts b/packages/api/src/filestorage/permission/services/onedrive/index.ts index 9372558e7..751dabe07 100644 --- a/packages/api/src/filestorage/permission/services/onedrive/index.ts +++ b/packages/api/src/filestorage/permission/services/onedrive/index.ts @@ -28,16 +28,8 @@ export class OnedriveService implements IPermissionService { data: SyncParam, ): Promise> { try { - const { linkedUserId, extra } = data; + const { connection, extra } = data; // TODO: where it comes from ?? extra?: { object_name: 'folder' | 'file'; value: string }, - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'onedrive', - vertical: 'filestorage', - }, - }); let remote_id; if (extra.object_name == 'folder') { const a = await this.prisma.fs_folders.findUnique({ diff --git a/packages/api/src/filestorage/permission/services/sharepoint/index.ts b/packages/api/src/filestorage/permission/services/sharepoint/index.ts index 2168542de..7db1a4661 100644 --- a/packages/api/src/filestorage/permission/services/sharepoint/index.ts +++ b/packages/api/src/filestorage/permission/services/sharepoint/index.ts @@ -28,16 +28,8 @@ export class SharepointService implements IPermissionService { data: SyncParam, ): Promise> { try { - const { linkedUserId, extra } = data; + const { connection, extra } = data; // TODO: where it comes from ?? extra?: { object_name: 'folder' | 'file'; value: string }, - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sharepoint', - vertical: 'filestorage', - }, - }); let remote_id; if (extra.object_name == 'folder') { const a = await this.prisma.fs_folders.findUnique({ diff --git a/packages/api/src/filestorage/sharedlink/services/box/index.ts b/packages/api/src/filestorage/sharedlink/services/box/index.ts index 20a4ff3f5..209bdc5ba 100644 --- a/packages/api/src/filestorage/sharedlink/services/box/index.ts +++ b/packages/api/src/filestorage/sharedlink/services/box/index.ts @@ -27,16 +27,9 @@ export class BoxService implements ISharedLinkService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, extra } = data; + const { connection, extra } = data; // TODO: where it comes from ?? extra?: { object_name: 'folder' | 'file'; value: string }, - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'box', - vertical: 'filestorage', - }, - }); let remote_id; if (extra.object_name == 'folder') { const a = await this.prisma.fs_folders.findUnique({ diff --git a/packages/api/src/filestorage/sharedlink/services/onedrive/index.ts b/packages/api/src/filestorage/sharedlink/services/onedrive/index.ts index bde2fc587..5baaf2b25 100644 --- a/packages/api/src/filestorage/sharedlink/services/onedrive/index.ts +++ b/packages/api/src/filestorage/sharedlink/services/onedrive/index.ts @@ -29,16 +29,8 @@ export class OnedriveService implements ISharedLinkService { data: SyncParam, ): Promise> { try { - const { linkedUserId, extra } = data; + const { connection, extra } = data; // TODO: where it comes from ?? extra?: { object_name: 'folder' | 'file'; value: string }, - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'onedrive', - vertical: 'filestorage', - }, - }); let remote_id; if (extra.object_name == 'folder') { const a = await this.prisma.fs_folders.findUnique({ diff --git a/packages/api/src/filestorage/sharedlink/services/sharepoint/index.ts b/packages/api/src/filestorage/sharedlink/services/sharepoint/index.ts index 679102d78..ef33fb9a5 100644 --- a/packages/api/src/filestorage/sharedlink/services/sharepoint/index.ts +++ b/packages/api/src/filestorage/sharedlink/services/sharepoint/index.ts @@ -29,16 +29,9 @@ export class SharepointService implements ISharedLinkService { data: SyncParam, ): Promise> { try { - const { linkedUserId, extra } = data; + const { connection, extra } = data; // TODO: where it comes from ?? extra?: { object_name: 'folder' | 'file'; value: string }, - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sharepoint', - vertical: 'filestorage', - }, - }); let remote_id; if (extra.object_name == 'folder') { const a = await this.prisma.fs_folders.findUnique({ diff --git a/packages/api/src/filestorage/user/services/box/index.ts b/packages/api/src/filestorage/user/services/box/index.ts index 3ed169813..2fe549916 100644 --- a/packages/api/src/filestorage/user/services/box/index.ts +++ b/packages/api/src/filestorage/user/services/box/index.ts @@ -26,16 +26,8 @@ export class BoxService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - // to sync all users we start from root user ("0") and recurse through it - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'box', - vertical: 'filestorage', - }, - }); const resp = await axios.get(`${connection.account_url}/2.0/users`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/filestorage/user/services/dropbox/index.ts b/packages/api/src/filestorage/user/services/dropbox/index.ts index 1d3d19f19..d63a43ae5 100644 --- a/packages/api/src/filestorage/user/services/dropbox/index.ts +++ b/packages/api/src/filestorage/user/services/dropbox/index.ts @@ -26,15 +26,7 @@ export class DropboxService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'dropbox', - vertical: 'filestorage', - }, - }); + const { connection } = data; // ref: https://www.dropbox.com/developers/documentation/http/teams#team-members-list const resp = await axios.post( diff --git a/packages/api/src/filestorage/user/services/onedrive/index.ts b/packages/api/src/filestorage/user/services/onedrive/index.ts index 185ac8fdc..d79608298 100644 --- a/packages/api/src/filestorage/user/services/onedrive/index.ts +++ b/packages/api/src/filestorage/user/services/onedrive/index.ts @@ -26,15 +26,7 @@ export class OnedriveService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'onedrive', - vertical: 'filestorage', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/v1.0/users`, { headers: { diff --git a/packages/api/src/filestorage/user/services/sharepoint/index.ts b/packages/api/src/filestorage/user/services/sharepoint/index.ts index d9bf83e8f..8fee6d025 100644 --- a/packages/api/src/filestorage/user/services/sharepoint/index.ts +++ b/packages/api/src/filestorage/user/services/sharepoint/index.ts @@ -26,15 +26,7 @@ export class SharepointService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sharepoint', - vertical: 'filestorage', - }, - }); + const { connection } = data; // remove /sites/site_id from account_url const url = connection.account_url.replace(/\/sites\/.+$/, ''); diff --git a/packages/api/src/hris/benefit/services/gusto/index.ts b/packages/api/src/hris/benefit/services/gusto/index.ts index 7686d0d78..8961df49a 100644 --- a/packages/api/src/hris/benefit/services/gusto/index.ts +++ b/packages/api/src/hris/benefit/services/gusto/index.ts @@ -28,15 +28,7 @@ export class GustoService implements IBenefitService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_employee } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gusto', - vertical: 'hris', - }, - }); + const { connection, id_employee } = data; const employee = await this.prisma.hris_employees.findUnique({ where: { diff --git a/packages/api/src/hris/company/services/deel/index.ts b/packages/api/src/hris/company/services/deel/index.ts index 6eb47d4ea..5fc49f390 100644 --- a/packages/api/src/hris/company/services/deel/index.ts +++ b/packages/api/src/hris/company/services/deel/index.ts @@ -37,15 +37,7 @@ export class DeelService implements ICompanyService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'deel', - vertical: 'hris', - }, - }); + const { connection } = data; const resp = await axios.get( `${connection.account_url}/rest/v2/legal-entities`, diff --git a/packages/api/src/hris/company/services/gusto/index.ts b/packages/api/src/hris/company/services/gusto/index.ts index bfc8bfa99..2adc1e4c9 100644 --- a/packages/api/src/hris/company/services/gusto/index.ts +++ b/packages/api/src/hris/company/services/gusto/index.ts @@ -37,15 +37,7 @@ export class GustoService implements ICompanyService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gusto', - vertical: 'hris', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/v1/token_info`, { headers: { diff --git a/packages/api/src/hris/employee/services/deel/index.ts b/packages/api/src/hris/employee/services/deel/index.ts index 966c3ff66..2d8726ccc 100644 --- a/packages/api/src/hris/employee/services/deel/index.ts +++ b/packages/api/src/hris/employee/services/deel/index.ts @@ -28,15 +28,7 @@ export class DeelService implements IEmployeeService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'deel', - vertical: 'hris', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/rest/v2/people`, { headers: { diff --git a/packages/api/src/hris/employee/services/gusto/index.ts b/packages/api/src/hris/employee/services/gusto/index.ts index 942f1a548..bf695d8f8 100644 --- a/packages/api/src/hris/employee/services/gusto/index.ts +++ b/packages/api/src/hris/employee/services/gusto/index.ts @@ -28,15 +28,7 @@ export class GustoService implements IEmployeeService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_company } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gusto', - vertical: 'hris', - }, - }); + const { connection, id_company } = data; const company = await this.prisma.hris_companies.findUnique({ where: { diff --git a/packages/api/src/hris/employee/services/sage/index.ts b/packages/api/src/hris/employee/services/sage/index.ts index be8e2937c..3b2d50cd1 100644 --- a/packages/api/src/hris/employee/services/sage/index.ts +++ b/packages/api/src/hris/employee/services/sage/index.ts @@ -28,15 +28,7 @@ export class SageService implements IEmployeeService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sage', - vertical: 'hris', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/api/employees`, { headers: { diff --git a/packages/api/src/hris/employerbenefit/services/gusto/index.ts b/packages/api/src/hris/employerbenefit/services/gusto/index.ts index 2024d7b4a..e43c09517 100644 --- a/packages/api/src/hris/employerbenefit/services/gusto/index.ts +++ b/packages/api/src/hris/employerbenefit/services/gusto/index.ts @@ -30,15 +30,7 @@ export class GustoService implements IEmployerBenefitService { data: SyncParam, ): Promise> { try { - const { linkedUserId, id_company } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gusto', - vertical: 'hris', - }, - }); + const { connection, id_company } = data; const company = await this.prisma.hris_companies.findUnique({ where: { diff --git a/packages/api/src/hris/group/services/deel/index.ts b/packages/api/src/hris/group/services/deel/index.ts index f593070b1..dcd4606ce 100644 --- a/packages/api/src/hris/group/services/deel/index.ts +++ b/packages/api/src/hris/group/services/deel/index.ts @@ -36,15 +36,7 @@ export class DeelService implements IGroupService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'deel', - vertical: 'hris', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/rest/v2/teams`, { headers: { diff --git a/packages/api/src/hris/group/services/gusto/index.ts b/packages/api/src/hris/group/services/gusto/index.ts index a2741d417..011921cb0 100644 --- a/packages/api/src/hris/group/services/gusto/index.ts +++ b/packages/api/src/hris/group/services/gusto/index.ts @@ -28,15 +28,7 @@ export class GustoService implements IGroupService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_company } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gusto', - vertical: 'hris', - }, - }); + const { connection, id_company } = data; const company = await this.prisma.hris_companies.findUnique({ where: { diff --git a/packages/api/src/hris/group/services/sage/index.ts b/packages/api/src/hris/group/services/sage/index.ts index 08dff20ec..f76e46ccc 100644 --- a/packages/api/src/hris/group/services/sage/index.ts +++ b/packages/api/src/hris/group/services/sage/index.ts @@ -36,15 +36,7 @@ export class SageService implements IGroupService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sage', - vertical: 'hris', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/api/teams`, { headers: { diff --git a/packages/api/src/hris/location/services/gusto/index.ts b/packages/api/src/hris/location/services/gusto/index.ts index 4787af093..f89c53a63 100644 --- a/packages/api/src/hris/location/services/gusto/index.ts +++ b/packages/api/src/hris/location/services/gusto/index.ts @@ -28,15 +28,7 @@ export class GustoService implements ILocationService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_employee } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gusto', - vertical: 'hris', - }, - }); + const { connection, id_employee } = data; const employee = await this.prisma.hris_employees.findUnique({ where: { diff --git a/packages/api/src/hris/timeoff/services/sage/index.ts b/packages/api/src/hris/timeoff/services/sage/index.ts index c83e2d187..408f9276b 100644 --- a/packages/api/src/hris/timeoff/services/sage/index.ts +++ b/packages/api/src/hris/timeoff/services/sage/index.ts @@ -36,15 +36,7 @@ export class SageService implements ITimeoffService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sage', - vertical: 'hris', - }, - }); + const { connection } = data; const resp = await axios.get( `${connection.account_url}/api/leave-management/requests`, diff --git a/packages/api/src/hris/timeoffbalance/services/sage/index.ts b/packages/api/src/hris/timeoffbalance/services/sage/index.ts index 61f928029..76ca5ee80 100644 --- a/packages/api/src/hris/timeoffbalance/services/sage/index.ts +++ b/packages/api/src/hris/timeoffbalance/services/sage/index.ts @@ -30,15 +30,7 @@ export class SageService implements ITimeoffBalanceService { data: SyncParam, ): Promise> { try { - const { linkedUserId, id_employee } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'sage', - vertical: 'hris', - }, - }); + const { connection, id_employee } = data; const employee = await this.prisma.hris_employees.findUnique({ where: { diff --git a/packages/api/src/ticketing/account/services/front/index.ts b/packages/api/src/ticketing/account/services/front/index.ts index 0c4b64361..3802906bb 100644 --- a/packages/api/src/ticketing/account/services/front/index.ts +++ b/packages/api/src/ticketing/account/services/front/index.ts @@ -27,15 +27,7 @@ export class FrontService implements IAccountService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'front', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/accounts`, { headers: { diff --git a/packages/api/src/ticketing/account/services/zendesk/index.ts b/packages/api/src/ticketing/account/services/zendesk/index.ts index 2c006ada0..c3bdbcc4d 100644 --- a/packages/api/src/ticketing/account/services/zendesk/index.ts +++ b/packages/api/src/ticketing/account/services/zendesk/index.ts @@ -29,15 +29,8 @@ export class ZendeskService implements IAccountService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, webhook_remote_identifier } = data; + const { connection, webhook_remote_identifier } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'ticketing', - }, - }); const remote_account_id = webhook_remote_identifier as string; const request_url = remote_account_id ? `${connection.account_url}/v2/organizations/${remote_account_id}.json` diff --git a/packages/api/src/ticketing/collection/services/github/index.ts b/packages/api/src/ticketing/collection/services/github/index.ts index 3197829aa..a4a853b28 100644 --- a/packages/api/src/ticketing/collection/services/github/index.ts +++ b/packages/api/src/ticketing/collection/services/github/index.ts @@ -13,49 +13,38 @@ import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class GithubService implements ICollectionService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - TicketingObject.collection.toUpperCase() + ':' + GithubService.name, - ); - this.registry.registerService('github', this); - } - - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + TicketingObject.collection.toUpperCase() + ':' + GithubService.name, + ); + this.registry.registerService('github', this); + } - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'github', - vertical: 'ticketing', - }, - }); - const resp = await axios.get( - `${connection.account_url}/user/repos`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - this.logger.log(`Synced github collections !`); + async sync(data: SyncParam): Promise> { + try { + const { connection } = data; + const resp = await axios.get(`${connection.account_url}/user/repos`, { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }); + this.logger.log(`Synced github collections !`); - return { - data: resp.data, - message: 'Github collections retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + return { + data: resp.data, + message: 'Github collections retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/ticketing/collection/services/gitlab/index.ts b/packages/api/src/ticketing/collection/services/gitlab/index.ts index 6373e26fb..511395ae2 100644 --- a/packages/api/src/ticketing/collection/services/gitlab/index.ts +++ b/packages/api/src/ticketing/collection/services/gitlab/index.ts @@ -27,15 +27,8 @@ export class GitlabService implements ICollectionService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gitlab', - vertical: 'ticketing', - }, - }); const resp = await axios.get( `${connection.account_url}/v4/projects?membership=true`, { diff --git a/packages/api/src/ticketing/collection/services/jira/index.ts b/packages/api/src/ticketing/collection/services/jira/index.ts index 12c9e2f3e..38edfd667 100644 --- a/packages/api/src/ticketing/collection/services/jira/index.ts +++ b/packages/api/src/ticketing/collection/services/jira/index.ts @@ -27,15 +27,7 @@ export class JiraService implements ICollectionService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'jira', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get( `${connection.account_url}/3/project/search`, diff --git a/packages/api/src/ticketing/collection/services/linear/index.ts b/packages/api/src/ticketing/collection/services/linear/index.ts index 357681884..5f2ecae32 100644 --- a/packages/api/src/ticketing/collection/services/linear/index.ts +++ b/packages/api/src/ticketing/collection/services/linear/index.ts @@ -27,23 +27,13 @@ export class LinearService implements ICollectionService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'linear', - vertical: 'ticketing', - }, - }); + const { connection } = data; const projectQuery = { - "query": "query { projects { nodes { id, name, description } }}" + query: 'query { projects { nodes { id, name, description } }}', }; - let resp = await axios.post( - `${connection.account_url}`, - projectQuery, { + const resp = await axios.post(`${connection.account_url}`, projectQuery, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( diff --git a/packages/api/src/ticketing/comment/services/front/index.ts b/packages/api/src/ticketing/comment/services/front/index.ts index 8a07c3ec7..ef76f9795 100644 --- a/packages/api/src/ticketing/comment/services/front/index.ts +++ b/packages/api/src/ticketing/comment/services/front/index.ts @@ -126,15 +126,8 @@ export class FrontService implements ICommentService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; + const { connection, id_ticket } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'front', - vertical: 'ticketing', - }, - }); //retrieve ticket remote id so we can retrieve the comments in the original software const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/comment/services/github/index.ts b/packages/api/src/ticketing/comment/services/github/index.ts index 058900445..43c748805 100644 --- a/packages/api/src/ticketing/comment/services/github/index.ts +++ b/packages/api/src/ticketing/comment/services/github/index.ts @@ -15,156 +15,155 @@ import { GithubTicketOutput } from '@ticketing/ticket/services/github/types'; @Injectable() export class GithubService implements ICommentService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - private utils: Utils, - ) { - this.logger.setContext( - TicketingObject.comment.toUpperCase() + ':' + GithubService.name, + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + private utils: Utils, + ) { + this.logger.setContext( + TicketingObject.comment.toUpperCase() + ':' + GithubService.name, + ); + this.registry.registerService('github', this); + } + + async addComment( + commentData: GithubCommentInput, + linkedUserId: string, + remoteIdTicket: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'github', + vertical: 'ticketing', + }, + }); + + // Here Github represent Attachment as URL in body of comment as Markdown so we do not have to store in attachement unified object. + + const ticket = await this.prisma.tcg_tickets.findFirst({ + where: { + remote_id: remoteIdTicket, + id_connection: connection.id_connection, + }, + select: { + collections: true, + id_tcg_ticket: true, + }, + }); + + // Retrieve the uuid of issue from remote_data + const remote_data = await this.prisma.remote_data.findFirst({ + where: { + ressource_owner_id: ticket.id_tcg_ticket as string, + }, + }); + + let res: any = []; + + const githubTicketOutput = JSON.parse( + remote_data.data, + ) as GithubTicketOutput; + + if ( + githubTicketOutput.number && + githubTicketOutput.repository.name && + githubTicketOutput.repository.owner.login + ) { + const resp = await axios.post( + `${connection.account_url}/repos/${githubTicketOutput.repository.owner.login}/${githubTicketOutput.repository.name}/issues/${githubTicketOutput.number}/comments`, + JSON.stringify(commentData), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, ); - this.registry.registerService('github', this); - } - - async addComment( - commentData: GithubCommentInput, - linkedUserId: string, - remoteIdTicket: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'github', - vertical: 'ticketing', - }, - }); - - // Here Github represent Attachment as URL in body of comment as Markdown so we do not have to store in attachement unified object. - - - const ticket = await this.prisma.tcg_tickets.findFirst({ - where: { - remote_id: remoteIdTicket, - id_connection: connection.id_connection, - }, - select: { - collections: true, - id_tcg_ticket: true, - }, - }); - - - - // Retrieve the uuid of issue from remote_data - const remote_data = await this.prisma.remote_data.findFirst({ - where: { - ressource_owner_id: ticket.id_tcg_ticket as string, - }, - }); - - let res: any = [] - - const githubTicketOutput = JSON.parse(remote_data.data) as GithubTicketOutput; - - if (githubTicketOutput.number && githubTicketOutput.repository.name && githubTicketOutput.repository.owner.login) { - const resp = await axios.post( - `${connection.account_url}/repos/${githubTicketOutput.repository.owner.login}/${githubTicketOutput.repository.name}/issues/${githubTicketOutput.number}/comments`, - JSON.stringify(commentData), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - - res = resp.data; - } - - - // const resp = await axios.post( - // `${connection.account_url}/projects/${remote_project_id}/issues/${iid}/notes`, - // JSON.stringify(data), - // { - // headers: { - // 'Content-Type': 'application/json', - // Authorization: `Bearer ${this.cryptoService.decrypt( - // connection.access_token, - // )}`, - // }, - // }, - // ); - - return { - data: res, - message: 'Github comment created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + res = resp.data; + } + + // const resp = await axios.post( + // `${connection.account_url}/projects/${remote_project_id}/issues/${iid}/notes`, + // JSON.stringify(data), + // { + // headers: { + // 'Content-Type': 'application/json', + // Authorization: `Bearer ${this.cryptoService.decrypt( + // connection.access_token, + // )}`, + // }, + // }, + // ); + + return { + data: res, + message: 'Github comment created', + statusCode: 201, + }; + } catch (error) { + throw error; } - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId, id_ticket } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'github', - vertical: 'ticketing', - }, - }); - //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 as string, - }, - select: { - remote_id: true, - collections: true, - }, - }); - - // Retrieve the uuid of issue from remote_data - const remote_data = await this.prisma.remote_data.findFirst({ - where: { - ressource_owner_id: id_ticket as string, - }, - }); - const githubTicketOutput = JSON.parse(remote_data.data) as GithubTicketOutput; - - let res = []; - if (githubTicketOutput.number && githubTicketOutput.repository.name && githubTicketOutput.repository.owner.login) { - const resp = await axios.get( - `${connection.account_url}/repos/${githubTicketOutput.repository.owner.login}/${githubTicketOutput.repository.name}/issues/${githubTicketOutput.number}/comments`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - res = resp.data; - } - - this.logger.log(`Synced github comments !`); - - return { - data: res, - message: 'Github comments retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + } + async sync(data: SyncParam): Promise> { + try { + const { connection, id_ticket } = data; + //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 as string, + }, + select: { + remote_id: true, + collections: true, + }, + }); + + // Retrieve the uuid of issue from remote_data + const remote_data = await this.prisma.remote_data.findFirst({ + where: { + ressource_owner_id: id_ticket as string, + }, + }); + const githubTicketOutput = JSON.parse( + remote_data.data, + ) as GithubTicketOutput; + + let res = []; + if ( + githubTicketOutput.number && + githubTicketOutput.repository.name && + githubTicketOutput.repository.owner.login + ) { + const resp = await axios.get( + `${connection.account_url}/repos/${githubTicketOutput.repository.owner.login}/${githubTicketOutput.repository.name}/issues/${githubTicketOutput.number}/comments`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + res = resp.data; + } + + this.logger.log(`Synced github comments !`); + + return { + data: res, + message: 'Github comments retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/ticketing/comment/services/gitlab/index.ts b/packages/api/src/ticketing/comment/services/gitlab/index.ts index 18b448015..11a2be1de 100644 --- a/packages/api/src/ticketing/comment/services/gitlab/index.ts +++ b/packages/api/src/ticketing/comment/services/gitlab/index.ts @@ -124,15 +124,8 @@ export class GitlabService implements ICommentService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; + const { connection, id_ticket } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gitlab', - vertical: 'ticketing', - }, - }); //retrieve ticket remote id so we can retrieve the comments in the original software const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/comment/services/gorgias/index.ts b/packages/api/src/ticketing/comment/services/gorgias/index.ts index a6fe3af1c..624b7dce6 100644 --- a/packages/api/src/ticketing/comment/services/gorgias/index.ts +++ b/packages/api/src/ticketing/comment/services/gorgias/index.ts @@ -64,15 +64,8 @@ export class GorgiasService implements ICommentService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; + const { connection, id_ticket } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gorgias', - vertical: 'ticketing', - }, - }); //retrieve ticket remote id so we can retrieve the comments in the original software const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/comment/services/jira/index.ts b/packages/api/src/ticketing/comment/services/jira/index.ts index 7411ee6b5..4dd1f7c80 100644 --- a/packages/api/src/ticketing/comment/services/jira/index.ts +++ b/packages/api/src/ticketing/comment/services/jira/index.ts @@ -118,15 +118,8 @@ export class JiraService implements ICommentService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; + const { connection, id_ticket } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'jira', - vertical: 'ticketing', - }, - }); //retrieve ticket remote id so we can retrieve the comments in the original software const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/comment/services/linear/index.ts b/packages/api/src/ticketing/comment/services/linear/index.ts index 1c1852d7f..0edd8f5a1 100644 --- a/packages/api/src/ticketing/comment/services/linear/index.ts +++ b/packages/api/src/ticketing/comment/services/linear/index.ts @@ -71,15 +71,7 @@ export class LinearService implements ICommentService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'linear', - vertical: 'ticketing', - }, - }); + const { connection, id_ticket } = data; const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/comment/services/zendesk/index.ts b/packages/api/src/ticketing/comment/services/zendesk/index.ts index 1e33918ca..08e25e697 100644 --- a/packages/api/src/ticketing/comment/services/zendesk/index.ts +++ b/packages/api/src/ticketing/comment/services/zendesk/index.ts @@ -121,15 +121,8 @@ export class ZendeskService implements ICommentService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; + const { connection, id_ticket } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'ticketing', - }, - }); //retrieve ticket remote id so we can retrieve the comments in the original software const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/contact/services/front/index.ts b/packages/api/src/ticketing/contact/services/front/index.ts index 43c897f52..67b036b34 100644 --- a/packages/api/src/ticketing/contact/services/front/index.ts +++ b/packages/api/src/ticketing/contact/services/front/index.ts @@ -26,15 +26,7 @@ export class FrontService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, account_id, webhook_remote_identifier } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'front', - vertical: 'ticketing', - }, - }); + const { connection, account_id, webhook_remote_identifier } = data; /*let remote_account_id; if (account_id) { // account_id can either be the remote or the panora id diff --git a/packages/api/src/ticketing/contact/services/gorgias/index.ts b/packages/api/src/ticketing/contact/services/gorgias/index.ts index 0bcfb7995..bcc420423 100644 --- a/packages/api/src/ticketing/contact/services/gorgias/index.ts +++ b/packages/api/src/ticketing/contact/services/gorgias/index.ts @@ -27,15 +27,7 @@ export class GorgiasService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gorgias', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/customers`, { headers: { diff --git a/packages/api/src/ticketing/contact/services/zendesk/index.ts b/packages/api/src/ticketing/contact/services/zendesk/index.ts index 2b3f8f60e..d8d899eef 100644 --- a/packages/api/src/ticketing/contact/services/zendesk/index.ts +++ b/packages/api/src/ticketing/contact/services/zendesk/index.ts @@ -29,15 +29,8 @@ export class ZendeskService implements IContactService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, webhook_remote_identifier } = data; + const { connection, webhook_remote_identifier } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'ticketing', - }, - }); let remote_contact_id; if (webhook_remote_identifier) { remote_contact_id = webhook_remote_identifier as string; diff --git a/packages/api/src/ticketing/tag/services/front/index.ts b/packages/api/src/ticketing/tag/services/front/index.ts index 6e9e0dacb..4ad4e6513 100644 --- a/packages/api/src/ticketing/tag/services/front/index.ts +++ b/packages/api/src/ticketing/tag/services/front/index.ts @@ -26,15 +26,7 @@ export class FrontService implements ITagService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'front', - vertical: 'ticketing', - }, - }); + const { connection, id_ticket } = data; /*const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/tag/services/github/index.ts b/packages/api/src/ticketing/tag/services/github/index.ts index f0e889a88..7c08ffddc 100644 --- a/packages/api/src/ticketing/tag/services/github/index.ts +++ b/packages/api/src/ticketing/tag/services/github/index.ts @@ -13,64 +13,56 @@ import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class GithubService implements ITagService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - TicketingObject.tag.toUpperCase() + ':' + GithubService.name, - ); - this.registry.registerService('github', this); - } - - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + TicketingObject.tag.toUpperCase() + ':' + GithubService.name, + ); + this.registry.registerService('github', this); + } - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'github', - vertical: 'ticketing', - }, - }); + async sync(data: SyncParam): Promise> { + try { + const { connection } = data; - const repos = await axios.get(`${connection.account_url}/user/repos`, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - let resp: any = []; - for (const repo of repos.data) { - if (repo.id) { - const tags = await axios.get( - `${connection.account_url}/repos/${repo.owner.login}/${repo.name}/labels`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - resp = [...resp, tags.data]; - } - } - this.logger.log(`Synced github tags !`); - - return { - data: resp.flat(), - message: 'Github tags retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; + const repos = await axios.get(`${connection.account_url}/user/repos`, { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }); + let resp: any = []; + for (const repo of repos.data) { + if (repo.id) { + const tags = await axios.get( + `${connection.account_url}/repos/${repo.owner.login}/${repo.name}/labels`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + resp = [...resp, tags.data]; } + } + this.logger.log(`Synced github tags !`); + + return { + data: resp.flat(), + message: 'Github tags retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/ticketing/tag/services/gitlab/index.ts b/packages/api/src/ticketing/tag/services/gitlab/index.ts index f2c1f0781..60228f438 100644 --- a/packages/api/src/ticketing/tag/services/gitlab/index.ts +++ b/packages/api/src/ticketing/tag/services/gitlab/index.ts @@ -27,15 +27,7 @@ export class GitlabService implements ITagService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gitlab', - vertical: 'ticketing', - }, - }); + const { connection } = data; const groups = await axios.get(`${connection.account_url}/v4/groups`, { headers: { diff --git a/packages/api/src/ticketing/tag/services/gorgias/index.ts b/packages/api/src/ticketing/tag/services/gorgias/index.ts index 95f121e9d..2430ba083 100644 --- a/packages/api/src/ticketing/tag/services/gorgias/index.ts +++ b/packages/api/src/ticketing/tag/services/gorgias/index.ts @@ -27,15 +27,7 @@ export class GorgiasService implements ITagService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gorgias', - vertical: 'ticketing', - }, - }); - + const { connection, id_ticket } = data; const ticket = await this.prisma.tcg_tickets.findUnique({ where: { id_tcg_ticket: id_ticket as string, diff --git a/packages/api/src/ticketing/tag/services/jira/index.ts b/packages/api/src/ticketing/tag/services/jira/index.ts index 44321ff76..bb52059ad 100644 --- a/packages/api/src/ticketing/tag/services/jira/index.ts +++ b/packages/api/src/ticketing/tag/services/jira/index.ts @@ -27,15 +27,7 @@ export class JiraService implements ITagService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'jira', - vertical: 'ticketing', - }, - }); + const { connection, id_ticket } = data; const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/tag/services/linear/index.ts b/packages/api/src/ticketing/tag/services/linear/index.ts index 7f5a6b072..65ec1882c 100644 --- a/packages/api/src/ticketing/tag/services/linear/index.ts +++ b/packages/api/src/ticketing/tag/services/linear/index.ts @@ -27,23 +27,13 @@ export class LinearService implements ITagService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'linear', - vertical: 'ticketing', - }, - }); + const { connection, id_ticket } = data; const labelQuery = { - "query": "query { issueLabels { nodes { id name } }}" + query: 'query { issueLabels { nodes { id name } }}', }; - let resp = await axios.post( - `${connection.account_url}`, - labelQuery, { + const resp = await axios.post(`${connection.account_url}`, labelQuery, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( diff --git a/packages/api/src/ticketing/tag/services/zendesk/index.ts b/packages/api/src/ticketing/tag/services/zendesk/index.ts index 9c8d612f4..6ce44f133 100644 --- a/packages/api/src/ticketing/tag/services/zendesk/index.ts +++ b/packages/api/src/ticketing/tag/services/zendesk/index.ts @@ -29,15 +29,7 @@ export class ZendeskService implements ITagService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, id_ticket } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'ticketing', - }, - }); + const { connection, id_ticket } = data; const ticket = await this.prisma.tcg_tickets.findUnique({ where: { diff --git a/packages/api/src/ticketing/tag/sync/sync.service.ts b/packages/api/src/ticketing/tag/sync/sync.service.ts index e5cfa0c1e..2af575166 100644 --- a/packages/api/src/ticketing/tag/sync/sync.service.ts +++ b/packages/api/src/ticketing/tag/sync/sync.service.ts @@ -6,7 +6,6 @@ import { CoreUnification } from '@@core/@core-services/unification/core-unificat import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; import { WebhookService } from '@@core/@core-services/webhooks/panora-webhooks/webhook.service'; import { FieldMappingService } from '@@core/field-mapping/field-mapping.service'; -import { ApiResponse } from '@@core/utils/types'; import { IBaseSync, SyncLinkedUserType } from '@@core/utils/types/interface'; import { OriginalTagOutput } from '@@core/utils/types/original/original.ticketing'; import { Injectable, OnModuleInit } from '@nestjs/common'; @@ -35,7 +34,7 @@ export class SyncService implements OnModuleInit, IBaseSync { this.registry.registerService('ticketing', 'tag', this); } onModuleInit() { -// + // } //function used by sync worker which populate our tcg_tags table diff --git a/packages/api/src/ticketing/team/services/front/index.ts b/packages/api/src/ticketing/team/services/front/index.ts index 9a2157b5c..07079d4eb 100644 --- a/packages/api/src/ticketing/team/services/front/index.ts +++ b/packages/api/src/ticketing/team/services/front/index.ts @@ -27,15 +27,7 @@ export class FrontService implements ITeamService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'front', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/teams`, { headers: { diff --git a/packages/api/src/ticketing/team/services/github/index.ts b/packages/api/src/ticketing/team/services/github/index.ts index 8bee342ce..f2b0f885a 100644 --- a/packages/api/src/ticketing/team/services/github/index.ts +++ b/packages/api/src/ticketing/team/services/github/index.ts @@ -13,47 +13,39 @@ import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class GithubService implements ITeamService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - TicketingObject.team.toUpperCase() + ':' + GithubService.name, - ); - this.registry.registerService('github', this); - } - - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + TicketingObject.team.toUpperCase() + ':' + GithubService.name, + ); + this.registry.registerService('github', this); + } - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'github', - vertical: 'ticketing', - }, - }); + async sync(data: SyncParam): Promise> { + try { + const { connection } = data; - const resp = await axios.get(`${connection.account_url}/user/teams`, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Synced github teams !`); + const resp = await axios.get(`${connection.account_url}/user/teams`, { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }); + this.logger.log(`Synced github teams !`); - return { - data: resp.data, - message: 'Github teams retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + return { + data: resp.data, + message: 'Github teams retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/ticketing/team/services/gorgias/index.ts b/packages/api/src/ticketing/team/services/gorgias/index.ts index b68b6dcb3..d6388fa6a 100644 --- a/packages/api/src/ticketing/team/services/gorgias/index.ts +++ b/packages/api/src/ticketing/team/services/gorgias/index.ts @@ -27,15 +27,7 @@ export class GorgiasService implements ITeamService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gorgias', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/teams`, { headers: { diff --git a/packages/api/src/ticketing/team/services/jira/index.ts b/packages/api/src/ticketing/team/services/jira/index.ts index 65d8b2d33..ec1af8fd2 100644 --- a/packages/api/src/ticketing/team/services/jira/index.ts +++ b/packages/api/src/ticketing/team/services/jira/index.ts @@ -27,15 +27,7 @@ export class JiraService implements ITeamService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'jira', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get( `${connection.account_url}/3/groups/picker`, diff --git a/packages/api/src/ticketing/team/services/linear/index.ts b/packages/api/src/ticketing/team/services/linear/index.ts index 952af6ad4..292f94e22 100644 --- a/packages/api/src/ticketing/team/services/linear/index.ts +++ b/packages/api/src/ticketing/team/services/linear/index.ts @@ -27,23 +27,13 @@ export class LinearService implements ITeamService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'linear', - vertical: 'ticketing', - }, - }); + const { connection } = data; const teamQuery = { - "query": "query { teams { nodes { id, name, description } }}" + query: 'query { teams { nodes { id, name, description } }}', }; - let resp = await axios.post( - `${connection.account_url}`, - teamQuery, { + const resp = await axios.post(`${connection.account_url}`, teamQuery, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( @@ -63,5 +53,3 @@ export class LinearService implements ITeamService { } } } - - diff --git a/packages/api/src/ticketing/team/services/zendesk/index.ts b/packages/api/src/ticketing/team/services/zendesk/index.ts index 90acaf969..14ae42825 100644 --- a/packages/api/src/ticketing/team/services/zendesk/index.ts +++ b/packages/api/src/ticketing/team/services/zendesk/index.ts @@ -29,15 +29,7 @@ export class ZendeskService implements ITeamService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/v2/groups.json`, { headers: { diff --git a/packages/api/src/ticketing/team/team.module.ts b/packages/api/src/ticketing/team/team.module.ts index 83c5b4ed0..d58330405 100644 --- a/packages/api/src/ticketing/team/team.module.ts +++ b/packages/api/src/ticketing/team/team.module.ts @@ -1,18 +1,17 @@ -import { LinearTeamMapper } from './services/linear/mappers'; -import { LinearService } from './services/linear'; -import { GithubTeamMapper } from './services/github/mappers'; -import { GithubService } from './services/github'; -import { BullQueueModule } from '@@core/@core-services/queues/queue.module'; import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; import { WebhookService } from '@@core/@core-services/webhooks/panora-webhooks/webhook.service'; import { Module } from '@nestjs/common'; import { Utils } from '@ticketing/@lib/@utils'; import { FrontService } from './services/front'; import { FrontTeamMapper } from './services/front/mappers'; +import { GithubService } from './services/github'; +import { GithubTeamMapper } from './services/github/mappers'; import { GorgiasService } from './services/gorgias'; import { GorgiasTeamMapper } from './services/gorgias/mappers'; import { JiraService } from './services/jira'; import { JiraTeamMapper } from './services/jira/mappers'; +import { LinearService } from './services/linear'; +import { LinearTeamMapper } from './services/linear/mappers'; import { ServiceRegistry } from './services/registry.service'; import { TeamService } from './services/team.service'; import { ZendeskService } from './services/zendesk'; @@ -46,4 +45,4 @@ import { TeamController } from './team.controller'; ], exports: [SyncService, ServiceRegistry, WebhookService], }) -export class TeamModule { } +export class TeamModule {} diff --git a/packages/api/src/ticketing/ticket/services/front/index.ts b/packages/api/src/ticketing/ticket/services/front/index.ts index 76c7d3a28..0e83680b5 100644 --- a/packages/api/src/ticketing/ticket/services/front/index.ts +++ b/packages/api/src/ticketing/ticket/services/front/index.ts @@ -156,15 +156,7 @@ export class FrontService implements ITicketService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'front', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/conversations`, { headers: { diff --git a/packages/api/src/ticketing/ticket/services/github/index.ts b/packages/api/src/ticketing/ticket/services/github/index.ts index 11dcb9703..f0614857f 100644 --- a/packages/api/src/ticketing/ticket/services/github/index.ts +++ b/packages/api/src/ticketing/ticket/services/github/index.ts @@ -14,112 +14,106 @@ import { GithubCollectionOutput } from '@ticketing/collection/services/github/ty @Injectable() export class GithubService implements ITicketService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - TicketingObject.ticket.toUpperCase() + ':' + GithubService.name, - ); - this.registry.registerService('github', this); - } - async addTicket( - ticketData: GithubTicketInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'github', - vertical: 'ticketing', - }, - }); - const { comment, collection_id, ...ticketD } = ticketData; - const DATA = { - ...ticketD, - }; + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + TicketingObject.ticket.toUpperCase() + ':' + GithubService.name, + ); + this.registry.registerService('github', this); + } + async addTicket( + ticketData: GithubTicketInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'github', + vertical: 'ticketing', + }, + }); + const { comment, collection_id, ...ticketD } = ticketData; + const DATA = { + ...ticketD, + }; - const remote_data = await this.prisma.remote_data.findFirst({ - where: { - ressource_owner_id: collection_id, - }, - }); + const remote_data = await this.prisma.remote_data.findFirst({ + where: { + ressource_owner_id: collection_id, + }, + }); - // let res: any = [] + // let res: any = [] - const githubCollectionOutput = JSON.parse(remote_data.data) as GithubCollectionOutput; + const githubCollectionOutput = JSON.parse( + remote_data.data, + ) as GithubCollectionOutput; - const resp = await axios.post( - `${connection.account_url}/repos/${githubCollectionOutput.owner.login}/${githubCollectionOutput.name}/issues`, - JSON.stringify(DATA), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - //insert comment - if (comment) { - const resp_ = await axios.post( - `${connection.account_url}/repos/${githubCollectionOutput.owner.login}/${githubCollectionOutput.name}/issues/${resp.data.number}/comments`, - JSON.stringify(comment), - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - } - return { - data: resp.data, - message: 'Github ticket created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + const resp = await axios.post( + `${connection.account_url}/repos/${githubCollectionOutput.owner.login}/${githubCollectionOutput.name}/issues`, + JSON.stringify(DATA), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + //insert comment + if (comment) { + const resp_ = await axios.post( + `${connection.account_url}/repos/${githubCollectionOutput.owner.login}/${githubCollectionOutput.name}/issues/${resp.data.number}/comments`, + JSON.stringify(comment), + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + } + return { + data: resp.data, + message: 'Github ticket created', + statusCode: 201, + }; + } catch (error) { + throw error; } - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'github', - vertical: 'ticketing', - }, - }); + } + async sync(data: SyncParam): Promise> { + try { + const { connection } = data; - const resp = await axios.get( - `${connection.account_url}/issues?filter=all&state=open`, - { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }, - ); - this.logger.log(`Synced github tickets !`); + const resp = await axios.get( + `${connection.account_url}/issues?filter=all&state=open`, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + this.logger.log(`Synced github tickets !`); - return { - data: resp.data, - message: 'Github tickets retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + return { + data: resp.data, + message: 'Github tickets retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/ticketing/ticket/services/gitlab/index.ts b/packages/api/src/ticketing/ticket/services/gitlab/index.ts index 03e5eb482..230441201 100644 --- a/packages/api/src/ticketing/ticket/services/gitlab/index.ts +++ b/packages/api/src/ticketing/ticket/services/gitlab/index.ts @@ -1,15 +1,14 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; import { TicketingObject } from '@ticketing/@lib/@types'; import { ITicketService } from '@ticketing/ticket/types'; -import { ApiResponse } from '@@core/utils/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ServiceRegistry } from '../registry.service'; import { GitlabTicketInput, GitlabTicketOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class GitlabService implements ITicketService { @@ -79,15 +78,7 @@ export class GitlabService implements ITicketService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gitlab', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get( `${connection.account_url}/v4/issues?scope=created_by_me&scope=assigned_to_me`, diff --git a/packages/api/src/ticketing/ticket/services/gorgias/index.ts b/packages/api/src/ticketing/ticket/services/gorgias/index.ts index 9ebf43535..55b92cc56 100644 --- a/packages/api/src/ticketing/ticket/services/gorgias/index.ts +++ b/packages/api/src/ticketing/ticket/services/gorgias/index.ts @@ -1,17 +1,16 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; import { TicketingObject } from '@ticketing/@lib/@types'; +import { Utils } from '@ticketing/@lib/@utils'; import { ITicketService } from '@ticketing/ticket/types'; -import { ApiResponse } from '@@core/utils/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; +import * as fs from 'fs'; import { ServiceRegistry } from '../registry.service'; import { GorgiasTicketInput, GorgiasTicketOutput } from './types'; -import * as fs from 'fs'; -import { SyncParam } from '@@core/utils/types/interface'; -import { Utils } from '@ticketing/@lib/@utils'; @Injectable() export class GorgiasService implements ITicketService { @@ -105,15 +104,7 @@ export class GorgiasService implements ITicketService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gorgias', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/tickets`, { headers: { diff --git a/packages/api/src/ticketing/ticket/services/jira/index.ts b/packages/api/src/ticketing/ticket/services/jira/index.ts index 48b37d446..7005e502d 100644 --- a/packages/api/src/ticketing/ticket/services/jira/index.ts +++ b/packages/api/src/ticketing/ticket/services/jira/index.ts @@ -1,17 +1,16 @@ import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ApiResponse } from '@@core/utils/types'; import { SyncParam } from '@@core/utils/types/interface'; import { Injectable } from '@nestjs/common'; import { TicketingObject } from '@ticketing/@lib/@types'; import { ITicketService } from '@ticketing/ticket/types'; import axios from 'axios'; -import { ServiceRegistry } from '../registry.service'; -import { JiraTicketInput, JiraTicketOutput } from './types'; import * as FormData from 'form-data'; import * as fs from 'fs'; +import { ServiceRegistry } from '../registry.service'; +import { JiraTicketInput, JiraTicketOutput } from './types'; @Injectable() export class JiraService implements ITicketService { @@ -231,15 +230,8 @@ export class JiraService implements ITicketService { } async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'jira', - vertical: 'ticketing', - }, - }); const resp = await axios.get(`${connection.account_url}/3/search`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/ticketing/ticket/services/linear/index.ts b/packages/api/src/ticketing/ticket/services/linear/index.ts index c1f9bf0af..01a181693 100644 --- a/packages/api/src/ticketing/ticket/services/linear/index.ts +++ b/packages/api/src/ticketing/ticket/services/linear/index.ts @@ -1,122 +1,113 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; import { TicketingObject } from '@ticketing/@lib/@types'; import { ITicketService } from '@ticketing/ticket/types'; -import { ApiResponse } from '@@core/utils/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ServiceRegistry } from '../registry.service'; import { LinearTicketInput, LinearTicketOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; -import { LinearCollectionOutput } from '@ticketing/collection/services/linear/types'; @Injectable() export class LinearService implements ITicketService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - TicketingObject.ticket.toUpperCase() + ':' + LinearService.name, - ); - this.registry.registerService('linear', this); - } - async addTicket( - ticketData: LinearTicketInput, - linkedUserId: string, - ): Promise> { - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'linear', - vertical: 'ticketing', - }, - }); + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + TicketingObject.ticket.toUpperCase() + ':' + LinearService.name, + ); + this.registry.registerService('linear', this); + } + async addTicket( + ticketData: LinearTicketInput, + linkedUserId: string, + ): Promise> { + try { + const connection = await this.prisma.connections.findFirst({ + where: { + id_linked_user: linkedUserId, + provider_slug: 'linear', + vertical: 'ticketing', + }, + }); - if (!ticketData.team.id) { - throw new ReferenceError( - `team_id is required field and cant be empty while creating a ticket.`, - ); - } + if (!ticketData.team.id) { + throw new ReferenceError( + `team_id is required field and cant be empty while creating a ticket.`, + ); + } - const createIssueMutation = { - "query": `mutation ($issueCreateInput: IssueCreateInput!) { issueCreate(input: $issueCreateInput) { issue { id title description dueDate parent{ id } state { name } project{ id } labels { nodes { id } } completedAt priorityLabel assignee { id } comments { nodes { id } } } }}`, - "variables": { - "issueCreateInput": { - "title": ticketData.title, - "description": ticketData.description, - "assigneeId": ticketData.assignee?.id, - "parentId": ticketData.parent?.id, - "labelIds": ticketData.labels?.nodes, - "projectId": ticketData.project?.id, - "sourceCommentId": ticketData.comments?.nodes, - "dueDate": ticketData.dueDate, - "teamId": ticketData.team.id - } - } - }; + const createIssueMutation = { + query: `mutation ($issueCreateInput: IssueCreateInput!) { issueCreate(input: $issueCreateInput) { issue { id title description dueDate parent{ id } state { name } project{ id } labels { nodes { id } } completedAt priorityLabel assignee { id } comments { nodes { id } } } }}`, + variables: { + issueCreateInput: { + title: ticketData.title, + description: ticketData.description, + assigneeId: ticketData.assignee?.id, + parentId: ticketData.parent?.id, + labelIds: ticketData.labels?.nodes, + projectId: ticketData.project?.id, + sourceCommentId: ticketData.comments?.nodes, + dueDate: ticketData.dueDate, + teamId: ticketData.team.id, + }, + }, + }; - let resp = await axios.post( - `${connection.account_url}`, - createIssueMutation, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Created linear ticket !`); + const resp = await axios.post( + `${connection.account_url}`, + createIssueMutation, + { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }, + ); + this.logger.log(`Created linear ticket !`); - return { - data: resp.data.data.issueCreate.issue, - message: 'Linear ticket created', - statusCode: 201, - }; - } catch (error) { - throw error; - } + return { + data: resp.data.data.issueCreate.issue, + message: 'Linear ticket created', + statusCode: 201, + }; + } catch (error) { + throw error; } - async sync(data: SyncParam): Promise> { - try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'linear', - vertical: 'ticketing', - }, - }); + } + async sync(data: SyncParam): Promise> { + try { + const { connection } = data; - const issueQuery = { - "query": "query { issues { nodes { id title description dueDate parent{ id } state { name } project{ id } labels { nodes { id } } completedAt priorityLabel assignee { id } comments { nodes { id } } } }}" - }; + const issueQuery = { + query: + 'query { issues { nodes { id title description dueDate parent{ id } state { name } project{ id } labels { nodes { id } } completedAt priorityLabel assignee { id } comments { nodes { id } } } }}', + }; - let resp = await axios.post( - `${connection.account_url}`, - issueQuery, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Synced linear tickets !`); + const resp = await axios.post(`${connection.account_url}`, issueQuery, { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }); + this.logger.log(`Synced linear tickets !`); - return { - data: resp.data.data.issues.nodes, - message: 'Linear tickets retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + return { + data: resp.data.data.issues.nodes, + message: 'Linear tickets retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/ticketing/ticket/services/zendesk/index.ts b/packages/api/src/ticketing/ticket/services/zendesk/index.ts index 8f50355e8..2053e7518 100644 --- a/packages/api/src/ticketing/ticket/services/zendesk/index.ts +++ b/packages/api/src/ticketing/ticket/services/zendesk/index.ts @@ -113,14 +113,7 @@ export class ZendeskService implements ITicketService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, webhook_remote_identifier } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'ticketing', - }, - }); + const { connection, webhook_remote_identifier } = data; const remote_ticket_id = webhook_remote_identifier as string; const request_url = remote_ticket_id diff --git a/packages/api/src/ticketing/user/services/front/index.ts b/packages/api/src/ticketing/user/services/front/index.ts index cbf61e220..734e37a1a 100644 --- a/packages/api/src/ticketing/user/services/front/index.ts +++ b/packages/api/src/ticketing/user/services/front/index.ts @@ -1,15 +1,14 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; -import { TicketingObject } from '@ticketing/@lib/@types'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; +import { TicketingObject } from '@ticketing/@lib/@types'; +import { IUserService } from '@ticketing/user/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ServiceRegistry } from '../registry.service'; -import { IUserService } from '@ticketing/user/types'; import { FrontUserOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class FrontService implements IUserService { @@ -27,15 +26,7 @@ export class FrontService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'front', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/teammates`, { headers: { diff --git a/packages/api/src/ticketing/user/services/github/index.ts b/packages/api/src/ticketing/user/services/github/index.ts index e4a3d75f5..66f048186 100644 --- a/packages/api/src/ticketing/user/services/github/index.ts +++ b/packages/api/src/ticketing/user/services/github/index.ts @@ -1,59 +1,50 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; -import { TicketingObject } from '@ticketing/@lib/@types'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; +import { TicketingObject } from '@ticketing/@lib/@types'; +import { IUserService } from '@ticketing/user/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ServiceRegistry } from '../registry.service'; -import { IUserService } from '@ticketing/user/types'; import { GithubUserOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class GithubService implements IUserService { - constructor( - private prisma: PrismaService, - private logger: LoggerService, - private cryptoService: EncryptionService, - private registry: ServiceRegistry, - ) { - this.logger.setContext( - TicketingObject.user.toUpperCase() + ':' + GithubService.name, - ); - this.registry.registerService('github', this); - } - - async sync(data: SyncParam): Promise> { - const { linkedUserId } = data; + constructor( + private prisma: PrismaService, + private logger: LoggerService, + private cryptoService: EncryptionService, + private registry: ServiceRegistry, + ) { + this.logger.setContext( + TicketingObject.user.toUpperCase() + ':' + GithubService.name, + ); + this.registry.registerService('github', this); + } - try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'github', - vertical: 'ticketing', - }, - }); + async sync(data: SyncParam): Promise> { + const { connection } = data; - const resp = await axios.get(`${connection.account_url}/users`, { - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${this.cryptoService.decrypt( - connection.access_token, - )}`, - }, - }); - this.logger.log(`Synced github users !`); + try { + const resp = await axios.get(`${connection.account_url}/users`, { + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${this.cryptoService.decrypt( + connection.access_token, + )}`, + }, + }); + this.logger.log(`Synced github users !`); - return { - data: resp.data, - message: 'github users retrieved', - statusCode: 200, - }; - } catch (error) { - throw error; - } + return { + data: resp.data, + message: 'github users retrieved', + statusCode: 200, + }; + } catch (error) { + throw error; } + } } diff --git a/packages/api/src/ticketing/user/services/gitlab/index.ts b/packages/api/src/ticketing/user/services/gitlab/index.ts index 4806b0e8d..940e39f3d 100644 --- a/packages/api/src/ticketing/user/services/gitlab/index.ts +++ b/packages/api/src/ticketing/user/services/gitlab/index.ts @@ -1,15 +1,14 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; -import { TicketingObject } from '@ticketing/@lib/@types'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; +import { TicketingObject } from '@ticketing/@lib/@types'; +import { IUserService } from '@ticketing/user/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ServiceRegistry } from '../registry.service'; -import { IUserService } from '@ticketing/user/types'; import { GitlabUserOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class GitlabService implements IUserService { @@ -26,17 +25,9 @@ export class GitlabService implements IUserService { } async sync(data: SyncParam): Promise> { - const { linkedUserId } = data; + const { connection } = data; try { - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gitlab', - vertical: 'ticketing', - }, - }); - const groups = await axios.get(`${connection.account_url}/v4/groups`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/ticketing/user/services/gorgias/index.ts b/packages/api/src/ticketing/user/services/gorgias/index.ts index 8f5e41fb4..1f98efaa1 100644 --- a/packages/api/src/ticketing/user/services/gorgias/index.ts +++ b/packages/api/src/ticketing/user/services/gorgias/index.ts @@ -1,15 +1,14 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; -import { TicketingObject } from '@ticketing/@lib/@types'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; +import { TicketingObject } from '@ticketing/@lib/@types'; +import { IUserService } from '@ticketing/user/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ServiceRegistry } from '../registry.service'; -import { IUserService } from '@ticketing/user/types'; import { GorgiasUserOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class GorgiasService implements IUserService { @@ -27,15 +26,7 @@ export class GorgiasService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'gorgias', - vertical: 'ticketing', - }, - }); + const { connection } = data; const resp = await axios.get(`${connection.account_url}/users`, { headers: { diff --git a/packages/api/src/ticketing/user/services/jira/index.ts b/packages/api/src/ticketing/user/services/jira/index.ts index 9d105b6d8..878e38d1e 100644 --- a/packages/api/src/ticketing/user/services/jira/index.ts +++ b/packages/api/src/ticketing/user/services/jira/index.ts @@ -1,15 +1,14 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; -import { TicketingObject } from '@ticketing/@lib/@types'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; +import { TicketingObject } from '@ticketing/@lib/@types'; +import { IUserService } from '@ticketing/user/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ServiceRegistry } from '../registry.service'; -import { IUserService } from '@ticketing/user/types'; import { JiraUserOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class JiraService implements IUserService { @@ -27,15 +26,8 @@ export class JiraService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; + const { connection } = data; - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'jira', - vertical: 'ticketing', - }, - }); const resp = await axios.get(`${connection.account_url}/3/users/search`, { headers: { 'Content-Type': 'application/json', diff --git a/packages/api/src/ticketing/user/services/linear/index.ts b/packages/api/src/ticketing/user/services/linear/index.ts index 09ec92f0e..541b25243 100644 --- a/packages/api/src/ticketing/user/services/linear/index.ts +++ b/packages/api/src/ticketing/user/services/linear/index.ts @@ -1,15 +1,14 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; -import { TicketingObject } from '@ticketing/@lib/@types'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; +import { TicketingObject } from '@ticketing/@lib/@types'; +import { IUserService } from '@ticketing/user/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; import { ServiceRegistry } from '../registry.service'; -import { IUserService } from '@ticketing/user/types'; import { LinearUserOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class LinearService implements IUserService { @@ -27,23 +26,13 @@ export class LinearService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'linear', - vertical: 'ticketing', - }, - }); + const { connection } = data; const userQuery = { - "query": "query { users { nodes { id, name, email } }}" + query: 'query { users { nodes { id, name, email } }}', }; - let resp = await axios.post( - `${connection.account_url}`, - userQuery, { + const resp = await axios.post(`${connection.account_url}`, userQuery, { headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( diff --git a/packages/api/src/ticketing/user/services/zendesk/index.ts b/packages/api/src/ticketing/user/services/zendesk/index.ts index 6902cba57..bdb4cd0bf 100644 --- a/packages/api/src/ticketing/user/services/zendesk/index.ts +++ b/packages/api/src/ticketing/user/services/zendesk/index.ts @@ -1,16 +1,15 @@ -import { Injectable } from '@nestjs/common'; +import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; +import { EnvironmentService } from '@@core/@core-services/environment/environment.service'; import { LoggerService } from '@@core/@core-services/logger/logger.service'; import { PrismaService } from '@@core/@core-services/prisma/prisma.service'; -import { EncryptionService } from '@@core/@core-services/encryption/encryption.service'; -import { TicketingObject } from '@ticketing/@lib/@types'; import { ApiResponse } from '@@core/utils/types'; +import { SyncParam } from '@@core/utils/types/interface'; +import { Injectable } from '@nestjs/common'; +import { TicketingObject } from '@ticketing/@lib/@types'; +import { IUserService } from '@ticketing/user/types'; import axios from 'axios'; -import { ActionType, handle3rdPartyServiceError } from '@@core/utils/errors'; -import { EnvironmentService } from '@@core/@core-services/environment/environment.service'; import { ServiceRegistry } from '../registry.service'; -import { IUserService } from '@ticketing/user/types'; import { ZendeskUserOutput } from './types'; -import { SyncParam } from '@@core/utils/types/interface'; @Injectable() export class ZendeskService implements IUserService { @@ -29,15 +28,7 @@ export class ZendeskService implements IUserService { async sync(data: SyncParam): Promise> { try { - const { linkedUserId, webhook_remote_identifier } = data; - - const connection = await this.prisma.connections.findFirst({ - where: { - id_linked_user: linkedUserId, - provider_slug: 'zendesk', - vertical: 'ticketing', - }, - }); + const { connection, webhook_remote_identifier } = data; const remote_user_id = webhook_remote_identifier as string; const request_url = remote_user_id ? `${connection.account_url}/v2/users/${remote_user_id}.json` diff --git a/packages/api/src/ticketing/user/user.module.ts b/packages/api/src/ticketing/user/user.module.ts index 4e078e84c..e450e850f 100644 --- a/packages/api/src/ticketing/user/user.module.ts +++ b/packages/api/src/ticketing/user/user.module.ts @@ -1,26 +1,25 @@ -import { LinearUserMapper } from './services/linear/mappers'; -import { LinearService } from './services/linear'; -import { GithubUserMapper } from './services/github/mappers'; -import { GithubService } from './services/github'; +import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; import { WebhookService } from '@@core/@core-services/webhooks/panora-webhooks/webhook.service'; import { Module } from '@nestjs/common'; +import { Utils } from '@ticketing/@lib/@utils'; import { FrontService } from './services/front'; +import { FrontUserMapper } from './services/front/mappers'; +import { GithubService } from './services/github'; +import { GithubUserMapper } from './services/github/mappers'; import { GitlabService } from './services/gitlab'; +import { GitlabUserMapper } from './services/gitlab/mappers'; import { GorgiasService } from './services/gorgias'; +import { GorgiasUserMapper } from './services/gorgias/mappers'; import { JiraService } from './services/jira'; +import { JiraUserMapper } from './services/jira/mappers'; +import { LinearService } from './services/linear'; +import { LinearUserMapper } from './services/linear/mappers'; import { ServiceRegistry } from './services/registry.service'; import { UserService } from './services/user.service'; import { ZendeskService } from './services/zendesk'; +import { ZendeskUserMapper } from './services/zendesk/mappers'; import { SyncService } from './sync/sync.service'; import { UserController } from './user.controller'; -import { IngestDataService } from '@@core/@core-services/unification/ingest-data.service'; -import { Utils } from '@ticketing/@lib/@utils'; -import { BullQueueModule } from '@@core/@core-services/queues/queue.module'; -import { FrontUserMapper } from './services/front/mappers'; -import { GitlabUserMapper } from './services/gitlab/mappers'; -import { GorgiasUserMapper } from './services/gorgias/mappers'; -import { JiraUserMapper } from './services/jira/mappers'; -import { ZendeskUserMapper } from './services/zendesk/mappers'; @Module({ controllers: [UserController], providers: [ @@ -49,4 +48,4 @@ import { ZendeskUserMapper } from './services/zendesk/mappers'; ], exports: [SyncService, ServiceRegistry, WebhookService, IngestDataService], }) -export class UserModule { } +export class UserModule {}