repo_name
string
dataset
string
owner
string
lang
string
func_name
string
code
string
docstring
string
url
string
sha
string
Panora
github_2023
panoratech
typescript
MappersRegistry.registerService
registerService( category_vertical: string, common_object: string, provider_name: string, service: any, ) { const compositeKey = this.createCompositeKey( category_vertical.toLowerCase().trim(), common_object.toLowerCase().trim(), provider_name.toLowerCase().trim(), ); this.serviceMap.set(compositeKey.toLowerCase().trim(), service); }
// Register a service with a composite key
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/registries/mappers.registry.ts#L12-L24
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
MappersRegistry.getService
getService( category_vertical: string, common_object: string, provider_name: string, ): any { const compositeKey = this.createCompositeKey( category_vertical.toLowerCase().trim(), common_object.toLowerCase().trim(), provider_name.toLowerCase().trim(), ); const service = this.serviceMap.get(compositeKey.toLowerCase().trim()); if (!service) { throw new Error( `Service not found for given keys: ${category_vertical}, ${common_object}, ${provider_name}`, ); } return service; }
// Retrieve a service using the composite key
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/registries/mappers.registry.ts#L27-L44
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
MappersRegistry.createCompositeKey
private createCompositeKey( category_vertical: string, common_object: string, provider_name: string, ): string { return `${category_vertical}_${common_object}_${provider_name}`; }
// Utility method to create a consistent key from three strings
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/registries/mappers.registry.ts#L47-L53
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
CoreUnification.unify
async unify<T extends UnifySourceType | UnifySourceType[]>({ sourceObject, targetType, providerName, vertical, connectionId, customFieldMappings, extraParams, }: { sourceObject: T; targetType: TargetObject; providerName: string; vertical: string; connectionId: string; //needed because inside mappers we might need it alongside remote_id to fetch a unified model in db customFieldMappings: { slug: string; remote_id: string; }[]; extraParams?: { [key: string]: any }; }): Promise<UnifyReturnType> { try { if (sourceObject == null) return []; let targetType_: TargetObject; switch (vertical.toLowerCase()) { case ConnectorCategory.Ecommerce: targetType_ = targetType as EcommerceObject; const ecommerceRegistry = this.registry.getService('ecommerce'); return ecommerceRegistry.unify({ sourceObject, targetType_, providerName, connectionId, customFieldMappings, extraParams, }); case ConnectorCategory.Crm: targetType_ = targetType as CrmObject; const crmRegistry = this.registry.getService('crm'); return crmRegistry.unify({ sourceObject, targetType_, providerName, connectionId, customFieldMappings, extraParams, }); case ConnectorCategory.Accounting: targetType_ = targetType as AccountingObject; const accountingRegistry = this.registry.getService('accounting'); return accountingRegistry.unify({ sourceObject, targetType_, providerName, connectionId, customFieldMappings, }); case ConnectorCategory.FileStorage: targetType_ = targetType as FileStorageObject; const filestorageRegistry = this.registry.getService('filestorage'); return filestorageRegistry.unify({ sourceObject, targetType_, providerName, connectionId, customFieldMappings, }); case ConnectorCategory.MarketingAutomation: targetType_ = targetType as MarketingAutomationObject; const marketingautomationRegistry = this.registry.getService( 'marketingautomation', ); return marketingautomationRegistry.unify({ sourceObject, targetType_, providerName, connectionId, customFieldMappings, }); case ConnectorCategory.Ticketing: targetType_ = targetType as TicketingObject; const ticketingRegistry = this.registry.getService('ticketing'); return ticketingRegistry.unify({ sourceObject, targetType_, providerName, connectionId, customFieldMappings, }); } } catch (error) { throw error; } }
/* to fetch data 3rdParties > [Panora] > SaaS */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/unification/core-unification.service.ts#L23-L115
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
CoreUnification.desunify
async desunify<T extends Unified>({ sourceObject, targetType, providerName, vertical, customFieldMappings, connectionId, }: { sourceObject: T; targetType: TargetObject; providerName: string; vertical: string; customFieldMappings?: { slug: string; remote_id: string; }[]; connectionId?: string; }): Promise<DesunifyReturnType> { try { let targetType_: TargetObject; switch (vertical.toLowerCase()) { case ConnectorCategory.Ecommerce: targetType_ = targetType as EcommerceObject; const ecommerceRegistry = this.registry.getService('ecommerce'); return ecommerceRegistry.desunify({ sourceObject, targetType_, providerName, customFieldMappings, }); case ConnectorCategory.Crm: targetType_ = targetType as CrmObject; const crmRegistry = this.registry.getService('crm'); return crmRegistry.desunify({ sourceObject, targetType_, providerName, customFieldMappings, }); case ConnectorCategory.Accounting: targetType_ = targetType as AccountingObject; const accountingRegistry = this.registry.getService('accounting'); return accountingRegistry.desunify({ sourceObject, targetType_, providerName, customFieldMappings, }); case ConnectorCategory.FileStorage: targetType_ = targetType as FileStorageObject; const filestorageRegistry = this.registry.getService('filestorage'); return filestorageRegistry.desunify({ sourceObject, targetType_, providerName, customFieldMappings, }); case ConnectorCategory.MarketingAutomation: targetType_ = targetType as MarketingAutomationObject; const marketingautomationRegistry = this.registry.getService( 'marketingautomation', ); return marketingautomationRegistry.desunify({ sourceObject, targetType_, providerName, customFieldMappings, }); case ConnectorCategory.Ticketing: targetType_ = targetType as TicketingObject; const ticketingRegistry = this.registry.getService('ticketing'); return ticketingRegistry.desunify({ sourceObject, targetType_, providerName, customFieldMappings, connectionId, }); } } catch (error) { throw error; } }
/* to insert data SaaS > [Panora] > 3rdParties */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/@core-services/unification/core-unification.service.ts#L123-L206
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
AuthService.generateApiKey
async generateApiKey( projectId: number | string, userId: number | string, ): Promise<{ access_token: string }> { try { const jwtPayload = { sub: userId, project_id: projectId, }; return { access_token: this.jwtService.sign(jwtPayload, { secret: process.env.JWT_SECRET, expiresIn: '1y', }), }; } catch (error) { throw error; } }
//must be called only if user is logged in
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/auth/auth.service.ts#L317-L335
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
ConnectionsStrategiesService.getConnectionStrategyData
async getConnectionStrategyData( projectId: string, type: string, attributes: string[], ) { const cs = await this.prisma.connection_strategies.findFirst({ where: { id_project: projectId, type: type, }, }); if (!cs) throw new ReferenceError('Connection strategy undefined !'); const entity = await this.prisma.cs_entities.findFirst({ where: { id_connection_strategy: cs.id_connection_strategy, }, }); if (!entity) throw new ReferenceError('Connection strategy entity undefined !'); const authValues: string[] = []; for (let i = 0; i < attributes.length; i++) { const attribute_slug = attributes[i]; //create all attributes (for oauth => client_id, client_secret) const attribute_ = await this.prisma.cs_attributes.findFirst({ where: { id_cs_entity: entity.id_cs_entity, attribute_slug: attribute_slug, }, }); if (!attribute_) throw new ReferenceError('Connection Strategy Attribute undefined !'); const value_ = await this.prisma.cs_values.findFirst({ where: { id_cs_attribute: attribute_.id_cs_attribute, }, }); if (!value_) throw new ReferenceError('Connection Strategy Value undefined !'); authValues.push(this.crypto.decrypt(value_.value)); } return authValues; }
// [client_id, client_secret] or [client_id, client_secret, subdomain] or [api_key]
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections-strategies/connections-strategies.service.ts#L146-L188
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
AccountingConnectionsService.handleCallBack
async handleCallBack( providerName: string, callbackOpts: CallbackParams, type_strategy: 'oauth2' | 'apikey' | 'basic', ) { try { const serviceName = providerName.toLowerCase(); const service = this.serviceRegistry.getService(serviceName); if (!service) { throw new ReferenceError(`Unknown provider, found ${providerName}`); } const data: Connection = await service.handleCallback(callbackOpts); const event = await this.prisma.events.create({ data: { id_connection: data.id_connection, id_project: data.id_project, id_event: uuidv4(), status: 'success', type: 'connection.created', method: 'GET', url: `/${type_strategy}/callback`, provider: providerName.toLowerCase(), direction: '0', timestamp: new Date(), id_linked_user: callbackOpts.linkedUserId, }, }); //directly send the webhook await this.webhook.dispatchWebhook( data, 'connection.created', callbackOpts.projectId, event.id_event, ); } catch (error) { throw error; } }
// this call pass 1. integrationID 2. CustomerId 3. Panora Api Key
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/accounting/services/accounting.connection.service.ts#L43-L82
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
AcceloConnectionService.handleTokenRefresh
async handleTokenRefresh(opts: RefreshParams) { try { const { connectionId, refreshToken, projectId } = opts; const formData = new URLSearchParams({ grant_type: 'refresh_token', refresh_token: this.cryptoService.decrypt(refreshToken), }); //const subdomain = 'panora'; //TODO: if custom oauth then get the actual domain from customer const CREDENTIALS = (await this.cService.getCredentials( projectId, this.type, )) as OAuth2AuthData; const res = await axios.post( `https://${CREDENTIALS.SUBDOMAIN}.api.accelo.com/oauth2/v0/token`, formData.toString(), { headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8', Authorization: `Basic ${Buffer.from( `${CREDENTIALS.CLIENT_ID}:${CREDENTIALS.CLIENT_SECRET}`, ).toString('base64')}`, }, }, ); const data: AcceloOAuthResponse = res.data; await this.prisma.connections.update({ where: { id_connection: connectionId, }, data: { access_token: this.cryptoService.encrypt(data.access_token), refresh_token: this.cryptoService.encrypt(data.refresh_token), expiration_timestamp: new Date( new Date().getTime() + Number(data.expires_in) * 1000, ), }, }); this.logger.log('OAuth credentials updated : accelo '); } catch (error) { throw error; } }
// It is not required for Accelo as it does not provide refresh_token
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/crm/services/accelo/accelo.service.ts#L193-L235
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
WealthboxConnectionService.passthrough
async passthrough( input: PassthroughInput, connectionId: string, ): Promise<PassthroughResponse> { try { const { headers } = input; const config = await this.constructPassthrough(input, connectionId); const connection = await this.prisma.connections.findUnique({ where: { id_connection: connectionId, }, }); config.headers['Authorization'] = `Basic ${Buffer.from( `${this.cryptoService.decrypt(connection.access_token)}:`, ).toString('base64')}`; config.headers = { ...config.headers, ...headers, }; return await this.retryService.makeRequest( { method: config.method, url: config.url, data: config.data, headers: config.headers, }, 'crm.wealthbox.passthrough', config.linkedUserId, ); } catch (error) { throw error; } }
// todo
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/crm/services/wealthbox/wealthbox.service.ts#L56-L92
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
EcommerceConnectionsService.handleCallBack
async handleCallBack( providerName: string, callbackOpts: CallbackParams, type_strategy: 'oauth2' | 'apikey' | 'basic', ) { try { const serviceName = providerName.toLowerCase(); const service = this.serviceRegistry.getService(serviceName); if (!service) { throw new ReferenceError(`Unknown provider, found ${providerName}`); } const data: Connection = await service.handleCallback(callbackOpts); const event = await this.prisma.events.create({ data: { id_connection: data.id_connection, id_project: data.id_project, id_event: uuidv4(), status: 'success', type: 'connection.created', method: 'GET', url: `/${type_strategy}/callback`, provider: providerName.toLowerCase(), direction: '0', timestamp: new Date(), id_linked_user: callbackOpts.linkedUserId, }, }); //directly send the webhook await this.webhook.deliverWebhook( data, 'connection.created', callbackOpts.projectId, event.id_event, ); } catch (error) { throw error; } }
// this call pass 1. integrationID 2. CustomerId 3. Panora Api Key
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/ecommerce/services/ecommerce.connection.service.ts#L43-L82
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
FilestorageConnectionsService.handleCallBack
async handleCallBack( providerName: string, callbackOpts: CallbackParams, type_strategy: 'oauth2' | 'apikey' | 'basic', ) { try { const serviceName = providerName.toLowerCase(); const service = this.serviceRegistry.getService(serviceName); if (!service) { throw new ReferenceError(`Unknown provider, found ${providerName}`); } const data: Connection = await service.handleCallback(callbackOpts); const event = await this.prisma.events.create({ data: { id_connection: data.id_connection, id_project: data.id_project, id_event: uuidv4(), status: 'success', type: 'connection.created', method: 'GET', url: `/${type_strategy}/callback`, provider: providerName.toLowerCase(), direction: '0', timestamp: new Date(), id_linked_user: callbackOpts.linkedUserId, }, }); //directly send the webhook await this.webhook.dispatchWebhook( data, 'connection.created', callbackOpts.projectId, event.id_event, ); } catch (error) { throw error; } }
// this call pass 1. integrationID 2. CustomerId 3. Panora Api Key
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/filestorage/services/filestorage.connection.service.ts#L44-L83
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
MarketingAutomationConnectionsService.handleCallBack
async handleCallBack( providerName: string, callbackOpts: CallbackParams, type_strategy: 'oauth2' | 'apikey' | 'basic', ) { try { const serviceName = providerName.toLowerCase(); const service = this.serviceRegistry.getService(serviceName); if (!service) { throw new ReferenceError(`Unknown provider, found ${providerName}`); } const data: Connection = await service.handleCallback(callbackOpts); const event = await this.prisma.events.create({ data: { id_connection: data.id_connection, id_project: data.id_project, id_event: uuidv4(), status: 'success', type: 'connection.created', method: 'GET', url: `/${type_strategy}/callback`, provider: providerName.toLowerCase(), direction: '0', timestamp: new Date(), id_linked_user: callbackOpts.linkedUserId, }, }); //directly send the webhook await this.webhook.dispatchWebhook( data, 'connection.created', callbackOpts.projectId, event.id_event, ); } catch (error) { throw error; } }
// this call pass 1. integrationID 2. CustomerId 3. Panora Api Key
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/marketingautomation/services/marketingautomation.connection.service.ts#L48-L87
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
ProductivityConnectionsService.handleCallBack
async handleCallBack( providerName: string, callbackOpts: CallbackParams, type_strategy: 'oauth2' | 'apikey' | 'basic', ) { try { const serviceName = providerName.toLowerCase(); const service = this.serviceRegistry.getService(serviceName); if (!service) { throw new ReferenceError(`Unknown provider, found ${providerName}`); } const data: Connection = await service.handleCallback(callbackOpts); const event = await this.prisma.events.create({ data: { id_connection: data.id_connection, id_project: data.id_project, id_event: uuidv4(), status: 'success', type: 'connection.created', method: 'GET', url: `/${type_strategy}/callback`, provider: providerName.toLowerCase(), direction: '0', timestamp: new Date(), id_linked_user: callbackOpts.linkedUserId, }, }); //directly send the webhook await this.webhook.dispatchWebhook( data, 'connection.created', callbackOpts.projectId, event.id_event, ); } catch (error) { throw error; } }
// this call pass 1. integrationID 2. CustomerId 3. Panora Api Key
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/productivity/services/productivity.connection.service.ts#L43-L82
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
TicketingConnectionsService.handleCallBack
async handleCallBack( providerName: string, callbackOpts: CallbackParams, type_strategy: 'oauth2' | 'apikey' | 'basic', ) { try { const serviceName = providerName.toLowerCase(); const service = this.serviceRegistry.getService(serviceName); if (!service) { throw new ReferenceError(`Unknown provider, found ${providerName}`); } const data: Connection = await service.handleCallback(callbackOpts); const event = await this.prisma.events.create({ data: { id_connection: data.id_connection, id_project: data.id_project, id_event: uuidv4(), status: 'success', type: 'connection.created', method: 'GET', url: `/${type_strategy}/callback`, provider: providerName.toLowerCase(), direction: '0', timestamp: new Date(), id_linked_user: callbackOpts.linkedUserId, }, }); //directly send the webhook await this.webhook.dispatchWebhook( data, 'connection.created', callbackOpts.projectId, event.id_event, ); } catch (error) { throw error; } }
// this call pass 1. integrationID 2. CustomerId 3. Panora Api Key
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/ticketing/services/ticketing.connection.service.ts#L44-L83
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GithubConnectionService.handleTokenRefresh
async handleTokenRefresh(opts: RefreshParams) { return; }
//TODO
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/connections/ticketing/services/github/github.service.ts#L178-L180
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
ProjectConnectorsService.updateProjectConnectors
async updateProjectConnectors( column: string, status: boolean, id_project: string, ) { try { const project = await this.prisma.projects.findFirst({ where: { id_project: id_project, }, }); if (!project) { throw new ReferenceError('Project undefined!'); } const existingPConnectors = await this.prisma.connector_sets.findFirst({ where: { id_connector_set: project.id_connector_set, }, }); if (!existingPConnectors) { throw new ReferenceError( `No connector set entry found for project ${id_project}`, ); } const updateData: any = { [column]: status, // Use computed property names to set the column dynamically }; const res = await this.prisma.connector_sets.update({ where: { id_connector_set: existingPConnectors.id_connector_set, }, data: updateData, }); return res; } catch (error) { throw error; } }
// it would be used when a new connector is built and needs to be insert inside our tbale
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/project-connectors/project-connectors.service.ts#L13-L54
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
ProjectConnectorsService.getConnectorsByProjectId
async getConnectorsByProjectId(id_project: string) { try { const project = await this.prisma.projects.findFirst({ where: { id_project, }, }); if (!project) { throw new ReferenceError('Project undefined!'); } const res = await this.prisma.connector_sets.findFirst({ where: { id_connector_set: project.id_connector_set, }, }); if (!res) { throw new ReferenceError('Connector set undefined!'); } return res; } catch (error) { throw error; } }
/*async createProjectConnectors(data: TypeCustom) { try { const updateData: any = { id_connector_set: uuidv4(), crm_hubspot: data.crm_hubspot, crm_zoho: data.crm_zoho, crm_zendesk: data.crm_zendesk, crm_pipedrive: data.crm_pipedrive, crm_attio: data.crm_attio, tcg_zendesk: data.tcg_zendesk, tcg_gorgias: data.tcg_gorgias, tcg_front: data.tcg_front, tcg_jira: data.tcg_jira, tcg_gitlab: data.tcg_gitlab, crm_close: data.crm_close, }; const res = await this.prisma.connector_sets.create({ data: updateData, }); return res; } catch (error) { throw error; } }*/
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/project-connectors/project-connectors.service.ts#L83-L107
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
CoreSyncService.initialSync
async initialSync(vertical: string, provider: string, linkedUserId: string) { try { switch (vertical) { case ConnectorCategory.Crm: await this.handleCrmSync(provider, linkedUserId); break; case ConnectorCategory.Ticketing: await this.handleTicketingSync(provider, linkedUserId); break; case ConnectorCategory.FileStorage: await this.handleFileStorageSync(provider, linkedUserId); break; case ConnectorCategory.Accounting: await this.handleAccountingSync(provider, linkedUserId); break; case ConnectorCategory.Ecommerce: await this.handleEcommerceSync(provider, linkedUserId); break; default: this.logger.warn(`Unsupported vertical: ${vertical}`); } } catch (error) { this.logger.error(`Error in initialSync: ${error.message}`, error); throw error; } }
//Initial sync which will execute when connection is successfully established
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/sync/sync.service.ts#L199-L224
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
CoreSyncService.handleAccountingSync
async handleAccountingSync(provider: string, linkedUserId: string) { return; }
// todo
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/sync/sync.service.ts#L227-L229
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
CoreSyncService.getSyncStatus
async getSyncStatus(vertical: string) { try { } catch (error) { throw error; } }
// we must have a sync_jobs table with 7 (verticals) rows, one of each is syncing details
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/@core/sync/sync.service.ts#L548-L553
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/account/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/address/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/attachment/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/balancesheet/sync/sync.service.ts#L41-L68
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/cashflowstatement/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/companyinfo/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/contact/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/creditnote/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/expense/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/incomestatement/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/invoice/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/item/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/journalentry/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/payment/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/phonenumber/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/purchaseorder/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/taxrate/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/trackingcategory/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/transaction/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ACCOUNTING_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/accounting/vendorcredit/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
Utils.mapTaskPriority
mapTaskPriority(priority?: string): 'HIGH' | 'MEDIUM' | 'LOW' { return priority === 'High' ? 'HIGH' : priority === 'Medium' ? 'MEDIUM' : 'LOW'; }
// not currently in use, but might be in the future
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/@lib/@utils/index.ts#L326-L332
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = CRM_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/company/sync/sync.service.ts#L42-L69
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.syncForLinkedUser
async syncForLinkedUser(param: SyncLinkedUserType) { try { const { integrationId, linkedUserId } = param; const service: ICompanyService = this.serviceRegistry.getService(integrationId); if (!service) { this.logger.log( `No service found in {vertical:crm, commonObject: company} for integration ID: ${integrationId}`, ); return; } await this.ingestService.syncForLinkedUser< UnifiedCrmCompanyOutput, OriginalCompanyOutput, ICompanyService >(integrationId, linkedUserId, 'crm', 'company', service, []); } catch (error) { throw error; } }
//todo: HANDLE DATA REMOVED FROM PROVIDER
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/company/sync/sync.service.ts#L72-L92
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = CRM_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/contact/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.syncForLinkedUser
async syncForLinkedUser(param: SyncLinkedUserType) { try { const { integrationId, linkedUserId } = param; const service: IContactService = this.serviceRegistry.getService(integrationId); if (!service) { this.logger.log( `No service found in {vertical:crm, commonObject: contact} for integration ID: ${integrationId}`, ); return; } await this.ingestService.syncForLinkedUser< UnifiedCrmContactOutput, OriginalContactOutput, IContactService >(integrationId, linkedUserId, 'crm', 'contact', service, []); } catch (error) { throw error; } }
//todo: HANDLE DATA REMOVED FROM PROVIDER
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/contact/sync/sync.service.ts#L73-L93
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = CRM_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/deal/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.syncForLinkedUser
async syncForLinkedUser(param: SyncLinkedUserType) { try { const { integrationId, linkedUserId } = param; const service: IDealService = this.serviceRegistry.getService(integrationId); if (!service) { this.logger.log( `No service found in {vertical:crm, commonObject: deal} for integration ID: ${integrationId}`, ); return; } await this.ingestService.syncForLinkedUser< UnifiedCrmDealOutput, OriginalDealOutput, IDealService >(integrationId, linkedUserId, 'crm', 'deal', service, []); } catch (error) { throw error; } }
//todo: HANDLE DATA REMOVED FROM PROVIDER
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/deal/sync/sync.service.ts#L70-L90
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
ZendeskService.addEngagement
async addEngagement( engagementData: ZendeskEngagementInput, linkedUserId: string, engagement_type: string, ): Promise<ApiResponse<ZendeskEngagementOutput>> { try { switch (engagement_type) { case 'CALL': return this.addCall(engagementData, linkedUserId); case 'MEETING': return; case 'EMAIL': return; default: break; } } catch (error) { throw error; } }
//ONLY CALLS FOR ZENDESK
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/engagement/services/zendesk/index.ts#L27-L46
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = CRM_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/engagement/sync/sync.service.ts#L46-L73
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.syncForLinkedUser
async syncForLinkedUser(data: SyncLinkedUserType) { try { const { integrationId, linkedUserId, engagement_type } = data; const service: IEngagementService = this.serviceRegistry.getService(integrationId); if (!service) { this.logger.log( `No service found in {vertical:crm, commonObject: engagement} for integration ID: ${integrationId}`, ); return; } await this.ingestService.syncForLinkedUser< UnifiedCrmEngagementOutput, OriginalEngagementOutput, IEngagementService >(integrationId, linkedUserId, 'crm', 'engagement', service, [ { param: engagement_type, paramName: 'engagement_type', shouldPassToService: true, shouldPassToIngest: true, }, ]); } catch (error) { throw error; } }
// todo engagement type
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/engagement/sync/sync.service.ts#L77-L104
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = CRM_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/note/sync/sync.service.ts#L46-L73
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.syncForLinkedUser
async syncForLinkedUser(param: SyncLinkedUserType) { try { const { integrationId, linkedUserId } = param; const service: INoteService = this.serviceRegistry.getService(integrationId); if (!service) { this.logger.log( `No service found in {vertical:crm, commonObject: note} for integration ID: ${integrationId}`, ); return; } await this.ingestService.syncForLinkedUser< UnifiedCrmNoteOutput, OriginalNoteOutput, INoteService >(integrationId, linkedUserId, 'crm', 'note', service, []); } catch (error) { throw error; } }
//todo: HANDLE DATA REMOVED FROM PROVIDER
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/note/sync/sync.service.ts#L76-L96
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = CRM_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/stage/sync/sync.service.ts#L44-L71
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.syncForLinkedUser
async syncForLinkedUser(data: SyncLinkedUserType) { try { const { integrationId, linkedUserId, deal_id } = data; const service: IStageService = this.serviceRegistry.getService(integrationId); if (!service) { this.logger.log( `No service found in {vertical:crm, commonObject: stage} for integration ID: ${integrationId}`, ); return; } await this.ingestService.syncForLinkedUser< UnifiedCrmStageOutput, OriginalStageOutput, IStageService >(integrationId, linkedUserId, 'crm', 'stage', service, [ { param: deal_id, paramName: 'deal_id', shouldPassToIngest: true, shouldPassToService: true, }, ]); } catch (error) { throw error; } }
//todo: HANDLE DATA REMOVED FROM PROVIDER
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/stage/sync/sync.service.ts#L74-L101
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = CRM_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/task/sync/sync.service.ts#L47-L74
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.syncForLinkedUser
async syncForLinkedUser(param: SyncLinkedUserType) { try { const { integrationId, linkedUserId } = param; const service: ITaskService = this.serviceRegistry.getService(integrationId); if (!service) { this.logger.log( `No service found in {vertical:crm, commonObject: task} for integration ID: ${integrationId}`, ); return; } await this.ingestService.syncForLinkedUser< UnifiedCrmTaskOutput, OriginalTaskOutput, ITaskService >(integrationId, linkedUserId, 'crm', 'task', service, []); } catch (error) { throw error; } }
//todo: HANDLE DATA REMOVED FROM PROVIDER
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/task/sync/sync.service.ts#L77-L97
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = CRM_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/user/sync/sync.service.ts#L46-L73
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.syncForLinkedUser
async syncForLinkedUser(param: SyncLinkedUserType) { try { const { integrationId, linkedUserId } = param; const service: IUserService = this.serviceRegistry.getService(integrationId); if (!service) { this.logger.log( `No service found in {vertical:crm, commonObject: user} for integration ID: ${integrationId}`, ); return; } await this.ingestService.syncForLinkedUser< UnifiedCrmUserOutput, OriginalUserOutput, IUserService >(integrationId, linkedUserId, 'crm', 'user', service, []); } catch (error) { throw error; } }
//todo: HANDLE DATA REMOVED FROM PROVIDER
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/crm/user/sync/sync.service.ts#L76-L96
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ECOMMERCE_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/ecommerce/customer/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ECOMMERCE_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/ecommerce/fulfillment/sync/sync.service.ts#L42-L69
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ECOMMERCE_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/ecommerce/order/sync/sync.service.ts#L41-L68
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = ECOMMERCE_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/ecommerce/product/sync/sync.service.ts#L43-L70
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.addDrive
async addDrive( driveData: DesunifyReturnType, linkedUserId: string, ): Promise<ApiResponse<OriginalDriveOutput>> { // No API to add drive in OneDrive return { data: null, message: 'Add drive not supported for OneDrive.', statusCode: 501, }; }
/** * Adds a new OneDrive drive. * @param driveData - Drive data to add. * @param linkedUserId - ID of the linked user. * @returns API response with the original drive output. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/drive/services/onedrive/index.ts#L38-L48
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.sync
async sync(data: SyncParam): Promise<ApiResponse<OnedriveDriveOutput[]>> { try { const { linkedUserId } = data; const connection = await this.prisma.connections.findFirst({ where: { id_linked_user: linkedUserId, provider_slug: 'onedrive', vertical: 'filestorage', }, }); const config: AxiosRequestConfig = { method: 'get', url: `${connection.account_url}/v1.0/me/drives`, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( connection.access_token, )}`, }, }; const resp: AxiosResponse = await this.makeRequestWithRetry(config); const drives: OnedriveDriveOutput[] = resp.data.value; this.logger.log(`Synced OneDrive drives successfully.`); return { data: drives, message: 'OneDrive drives retrieved successfully.', statusCode: 200, }; } catch (error: any) { this.logger.error( `Error syncing OneDrive drives: ${error.message}`, error, ); throw error; } }
/** * Synchronizes OneDrive drives. * @param data - Synchronization parameters. * @returns API response with an array of OneDrive drive outputs. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/drive/services/onedrive/index.ts#L55-L95
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.makeRequestWithRetry
private async makeRequestWithRetry( config: AxiosRequestConfig, ): Promise<AxiosResponse> { let attempts = 0; let backoff: number = this.INITIAL_BACKOFF_MS; while (attempts < this.MAX_RETRIES) { try { const response: AxiosResponse = await axios(config); return response; } catch (error: any) { attempts++; // Handle rate limiting (429) and server errors (500+) if ( (error.response && error.response.status === 429) || (error.response && error.response.status >= 500) || error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT' || error.response?.code === 'ETIMEDOUT' ) { const retryAfter = this.getRetryAfter( error.response?.headers['retry-after'], ); const delayTime: number = Math.max(retryAfter * 1000, backoff); this.logger.warn( `Request failed with ${ error.code || error.response?.status }. Retrying in ${delayTime}ms (Attempt ${attempts}/${ this.MAX_RETRIES })`, ); await this.delay(delayTime); backoff *= 2; // Exponential backoff continue; } // Handle other errors this.logger.error(`Request failed: ${error.message}`, error); throw error; } } this.logger.error( 'Max retry attempts reached. Request failed.', OnedriveService.name, ); throw new Error('Max retry attempts reached.'); }
/** * Makes an HTTP request with retry logic for handling 500 and 429 errors. * @param config - Axios request configuration. * @returns Axios response. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/drive/services/onedrive/index.ts#L102-L152
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.getRetryAfter
private getRetryAfter(retryAfterHeader: string | undefined): number { if (!retryAfterHeader) { return 1; // Default to 1 second if header is missing } const retryAfterSeconds: number = parseInt(retryAfterHeader, 10); return isNaN(retryAfterSeconds) ? 1 : retryAfterSeconds; }
/** * Parses the Retry-After header to determine the wait time. * @param retryAfterHeader - Value of the Retry-After header. * @returns Retry delay in seconds. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/drive/services/onedrive/index.ts#L159-L166
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.delay
private delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); }
/** * Delays execution for the specified duration. * @param ms - Duration in milliseconds. * @returns Promise that resolves after the delay. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/drive/services/onedrive/index.ts#L173-L175
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = FILESTORAGE_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/drive/sync/sync.service.ts#L40-L67
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GoogleDriveService.sync
async sync(data: SyncParam, pageToken?: string) { const { linkedUserId, custom_field_mappings, ingestParams } = data; const connection = await this.prisma.connections.findFirst({ where: { id_linked_user: linkedUserId, provider_slug: 'googledrive', vertical: 'filestorage', }, }); if (!connection) return; const auth = new OAuth2Client(); auth.setCredentials({ access_token: this.cryptoService.decrypt(connection.access_token), }); const drive = google.drive({ version: 'v3', auth }); const lastSyncTime = await this.getLastSyncTime(connection.id_connection); const isFirstSync = !lastSyncTime || pageToken; let syncCompleted = false; if (isFirstSync) { // Start or continuation of initial sync const { filesToSync: files, nextPageToken } = await this.getFilesToSync( drive, pageToken, ); // Process the files fetched in the current batch if (files.length > 0) { await this.ingestFiles( files, connection.id_connection, drive, null, custom_field_mappings, ingestParams, ); } if (nextPageToken) { // Add the next pageToken to the queue await this.bullQueueService .getThirdPartyDataIngestionQueue() .add('fs_file_googledrive', { ...data, pageToken: nextPageToken, connectionId: connection.id_connection, }); } else { syncCompleted = true; } } else { // incremental sync using changes api const { filesToSync, moreChangesToFetch, remote_cursor } = await this.getFilesToSyncFromChangesApi(drive, connection); await this.ingestFiles( filesToSync, connection.id_connection, drive, remote_cursor, custom_field_mappings, ingestParams, ); if (moreChangesToFetch) { await this.bullQueueService .getThirdPartyDataIngestionQueue() .add('fs_file_googledrive', { ...data, }); } else { syncCompleted = true; } } if (syncCompleted) { this.logger.log( `Googledrive files sync completed for user: ${linkedUserId}.`, ); } return { data: [], message: 'Google Drive sync completed for this batch', statusCode: 200, }; }
/** * Syncs files from Google Drive to the local database * @param data - Parameters required for syncing * @param pageToken - Used for continuation of initial sync */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/services/googledrive/index.ts#L146-L235
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GoogleDriveService.getFilesToSyncFromChangesApi
async getFilesToSyncFromChangesApi( drive: ReturnType<typeof google.drive>, connection: any, maxApiCalls = 10, // number of times we use nextPageToken ) { const filesToSync: GoogleDriveFileOutput[] = []; let apiCallCount = 0; let pageToken: string | undefined; let newRemoteCursor: string | undefined; // Get initial cursor pageToken = await this.getRemoteCursor(drive, connection.id_connection); do { const response = await this.rateLimitedRequest(() => drive.changes.list({ pageToken, supportsAllDrives: true, includeItemsFromAllDrives: true, pageSize: 1000, fields: 'nextPageToken, newStartPageToken, changes(file(id,name,mimeType,createdTime,modifiedTime,size,parents,webViewLink,driveId,trashed,permissionIds))', }), ); const { changes, nextPageToken, newStartPageToken } = response.data; const batchFiles = changes .filter( (change) => change.file?.mimeType !== 'application/vnd.google-apps.folder', ) .map((change) => change.file); filesToSync.push(...(batchFiles as GoogleDriveFileOutput[])); // Update pageToken for next iteration pageToken = nextPageToken; newRemoteCursor = newStartPageToken || nextPageToken; apiCallCount++; } while (pageToken && apiCallCount < maxApiCalls); return { filesToSync, moreChangesToFetch: !!pageToken, // true if there's still a next page remote_cursor: newRemoteCursor, }; }
// For incremental syncs
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/services/googledrive/index.ts#L238-L285
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GoogleDriveService.assignDriveIds
private async assignDriveIds( files: GoogleDriveFileOutput[], drive: ReturnType<typeof google.drive>, ): Promise<GoogleDriveFileOutput[]> { const rootDriveId = await this.rateLimitedRequest(() => drive.files .get({ fileId: 'root', fields: 'id', }) .then((res) => res.data.id), ); files.forEach((file) => { file.driveId = file.driveId || rootDriveId; }); return files; }
/** * Assigns driveId as root to files that don't have one. * @param files Array of Google Drive files. * @param auth OAuth2 client for Google Drive API. * @returns Array of Google Drive files with driveId assigned. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/services/googledrive/index.ts#L376-L394
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.sync
async sync( data: SyncParam, deltaLink?: string, ): Promise<ApiResponse<OnedriveFileOutput[]>> { try { const { linkedUserId, custom_field_mappings, ingestParams, id_folder } = data; const connection = await this.prisma.connections.findFirst({ where: { id_linked_user: linkedUserId, provider_slug: 'onedrive', vertical: 'filestorage', }, }); // if id_folder is provided, sync only the files in the specified folder if (id_folder) { const folder = await this.prisma.fs_folders.findUnique({ where: { id_fs_folder: id_folder as string, }, select: { remote_id: true, }, }); if (folder) { const files = await this.syncFolder(connection, folder.remote_id); return { data: files, message: 'OneDrive files retrieved from specified folder', statusCode: 200, }; } } // if deltaLink is provided if (deltaLink) { this.logger.log(`Syncing OneDrive files from deltaLink: ${deltaLink}`); let files: OnedriveFileOutput[] = []; let nextDeltaLink: string | null = null; try { const { files: batchFiles, nextDeltaLink: batchNextDeltaLink } = await this.getFilesToSync(connection, deltaLink, 10); files = batchFiles; nextDeltaLink = batchNextDeltaLink; } catch (error: any) { if (error.response?.status === 410) { // Delta token expired, start fresh sync const newDeltaLink = `${connection.account_url}/v1.0/me/drive/root/delta?$top=1000`; return this.sync(data, newDeltaLink); } await this.bullQueueService .getSyncJobsQueue() .add('fs_file_onedrive', { ...data, deltaLink: deltaLink, connectionId: connection.id_connection, }); this.logger.error( `Got 410 error while syncing OneDrive files. Added sync from /delta endpoint to queue to retry.`, error, ); } if (files.length > 0) { const ingestedFiles = await this.ingestFiles( files, connection, custom_field_mappings, ingestParams, ); this.logger.log( `Ingested ${ingestedFiles.length} files from OneDrive.`, ); } // more files to sync if (nextDeltaLink) { await this.bullQueueService .getThirdPartyDataIngestionQueue() .add('fs_file_onedrive', { ...data, deltaLink: nextDeltaLink, connectionId: connection.id_connection, }); } else { this.logger.log(`No more files to sync from OneDrive.`); } } else { const lastSyncTime = await this.getLastSyncTime( connection.id_connection, ); const deltaLink = lastSyncTime ? `${ connection.account_url }/v1.0/me/drive/root/delta?$top=1000&token=${lastSyncTime.toISOString()}` : `${connection.account_url}/v1.0/me/drive/root/delta?$top=1000`; // if no last sync time, get all files await this.sync(data, deltaLink); } return { data: [], message: 'OneDrive files retrieved', statusCode: 200, }; } catch (error) { console.log(error); this.logger.error( `Error syncing OneDrive files: ${error.message}`, error, ); throw error; } }
// todo: add addFile method
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/services/onedrive/index.ts#L43-L162
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.ingestPermissionsForFiles
private async ingestPermissionsForFiles( allFiles: OnedriveFileOutput[], connection: Connection, ): Promise<OnedriveFileOutput[]> { const allPermissions: OnedrivePermissionOutput[] = []; const fileIdToRemotePermissionIdMap: Map<string, string[]> = new Map(); const batchSize = 4; // simultaneous requests const files = allFiles.filter((f) => !f.deleted); for (let i = 0; i < files.length; i += batchSize) { const batch = files.slice(i, i + batchSize); const permissions = await Promise.all( batch.map(async (file) => { const permissionConfig: AxiosRequestConfig = { timeout: 30000, method: 'get', url: `${connection.account_url}/v1.0/me/drive/items/${file.id}/permissions`, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( connection.access_token, )}`, }, }; const resp = await this.makeRequestWithRetry(permissionConfig); const permissions = resp.data.value; fileIdToRemotePermissionIdMap.set( file.id, permissions.map((p) => p.id), ); return permissions; }), ); this.delay(1000); // delay to avoid rate limiting allPermissions.push(...permissions.flat()); } const uniquePermissions = Array.from( new Map( allPermissions.map((permission) => [permission.id, permission]), ).values(), ); await this.assignUserAndGroupIdsToPermissions(uniquePermissions); const syncedPermissions = await this.ingestService.ingestData< UnifiedFilestoragePermissionOutput, OnedrivePermissionOutput >( uniquePermissions, 'onedrive', connection.id_connection, 'filestorage', 'permission', ); this.logger.log( `Ingested ${syncedPermissions.length} permissions for files.`, ); const permissionIdMap: Map<string, string> = new Map( syncedPermissions.map((permission) => [ permission.remote_id, permission.id_fs_permission, ]), ); files.forEach((file) => { if (fileIdToRemotePermissionIdMap.has(file.id)) { file.internal_permissions = fileIdToRemotePermissionIdMap .get(file.id) ?.map((permission) => permissionIdMap.get(permission)) .filter((id) => id !== undefined); } }); return allFiles; }
/** * Ingests and assigns permissions for files. * @param allFiles - Array of OnedriveFileOutput to process. * @param connection - The connection object. * @returns The updated array of OnedriveFileOutput with ingested permissions. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/services/onedrive/index.ts#L271-L352
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.makeRequestWithRetry
private async makeRequestWithRetry( config: AxiosRequestConfig, ): Promise<AxiosResponse> { let attempts = 0; let backoff: number = this.INITIAL_BACKOFF_MS; while (attempts < this.MAX_RETRIES) { try { const response: AxiosResponse = await axios(config); return response; } catch (error: any) { attempts++; // Handle rate limiting if (error.response && error.response.status === 429) { const retryAfter: number = this.getRetryAfter( error.response.headers['retry-after'], ); const delayTime: number = Math.max(retryAfter * 1000, backoff); this.logger.warn( `Rate limit hit. Retrying request in ${delayTime}ms (Attempt ${attempts}/${this.MAX_RETRIES})`, ); await this.delay(delayTime); backoff *= 2; // Exponential backoff continue; } // Handle timeout errors if ( error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT' || error.response?.code === 'ETIMEDOUT' ) { const delayTime: number = backoff; this.logger.warn( `Request timeout. Retrying in ${delayTime}ms (Attempt ${attempts}/${this.MAX_RETRIES})`, ); await this.delay(delayTime); backoff *= 2; continue; } // Handle server errors (500+) if (error.response && error.response.status >= 500) { const delayTime: number = backoff; this.logger.warn( `Server error ${error.response.status}. Retrying in ${delayTime}ms (Attempt ${attempts}/${this.MAX_RETRIES})`, ); await this.delay(delayTime); backoff *= 2; continue; } // handle 410 gone errors if (error.response?.status === 410 && config.url.includes('delta')) { // todo: handle 410 gone errors } throw error; } } this.logger.error( 'Max retry attempts reached. Request failed.', 'onedrive', 'makeRequestWithRetry', ); throw new Error('Max retry attempts reached.'); }
/** * Makes an HTTP request with rate limit handling using exponential backoff. * @param config - Axios request configuration. * @returns Axios response. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/services/onedrive/index.ts#L486-L560
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.getRetryAfter
private getRetryAfter(retryAfterHeader: string | undefined): number { if (!retryAfterHeader) { return 1; // Default to 1 second if header is missing } const retryAfterSeconds: number = parseInt(retryAfterHeader, 10); return isNaN(retryAfterSeconds) ? 1 : retryAfterSeconds; }
/** * Parses the Retry-After header to determine the wait time. * @param retryAfterHeader - Value of the Retry-After header. * @returns Retry delay in seconds. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/services/onedrive/index.ts#L567-L574
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.delay
private delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); }
/** * Delays execution for the specified duration. * @param ms - Duration in milliseconds. * @returns Promise that resolves after the delay. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/services/onedrive/index.ts#L581-L583
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = FILESTORAGE_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/file/sync/sync.service.ts#L44-L71
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
fetchFoldersForParent
const fetchFoldersForParent = async ( parentId: string | null = null, driveId: string, ): Promise<GoogleDriveFolderOutput[]> => { const folders: GoogleDriveFolderOutput[] = []; let pageToken: string | null = null; const buildQuery = (parentId: string | null, driveId: string): string => { const baseQuery = `mimeType='application/vnd.google-apps.folder'`; return parentId ? `${baseQuery} and '${parentId}' in parents` : `${baseQuery} and '${driveId}' in parents`; }; try { do { const response = (await this.executeWithRetry(() => drive.files.list({ q: buildQuery(parentId, driveId), fields: 'nextPageToken, files(id, name, parents, createdTime, modifiedTime, driveId, webViewLink, permissionIds, trashed)', pageToken, includeItemsFromAllDrives: true, supportsAllDrives: true, orderBy: 'modifiedTime', ...(driveId !== 'root' && { driveId, corpora: 'drive', }), }), )) as unknown as GoogleDriveListResponse; if (response.data.files?.length) { folders.push(...response.data.files); } pageToken = response.data.nextPageToken ?? null; } while (pageToken); // Set default driveId for folders that don't have one folders.forEach((folder) => { folder.driveId = folder.driveId || rootDriveId; }); return folders; } catch (error) { throw new Error( `Error fetching Google Drive folders: ${error.message}`, ); } };
// Helper function to fetch folders for a specific parent ID or root
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/googledrive/index.ts#L182-L232
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
populateFolders
async function populateFolders( parentId: string | null = null, // Parent Folder ID returned by google drive api internalParentId: string | null = null, // Parent Folder ID in panora db level = 0, allFolders: GoogleDriveFolderOutput[] = [], driveId: string, ): Promise<void> { const currentLevelFolders = await fetchFoldersForParent( parentId, driveId, ); currentLevelFolders.forEach((folder) => { folder.internal_id = uuidv4(); folder.internal_parent_folder_id = internalParentId; }); allFolders.push(...currentLevelFolders); await Promise.all( currentLevelFolders.map((folder) => populateFolders( folder.id, folder.internal_id, level + 1, allFolders, driveId, ), ), ); }
// Recursive function to populate folders level by level
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/googledrive/index.ts#L235-L265
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GoogleDriveFolderService.ingestPermissionsForFolders
async ingestPermissionsForFolders( folders: GoogleDriveFolderOutput[], connectionId: string, auth: OAuth2Client, ): Promise<GoogleDriveFolderOutput[]> { if (folders.length === 0) { this.logger.log('No folders provided for ingesting permissions.'); return folders; } try { // Extract all permissions from the folders const permissionsIds: string[] = Array.from( new Set( folders.reduce<string[]>((accumulator, folder) => { if (folder.permissionIds?.length) { accumulator.push(...folder.permissionIds); } return accumulator; }, []), ), ); if (permissionsIds.length === 0) { this.logger.log('No permissions found in the provided folders.'); return folders; } const uniquePermissions = await this.fetchPermissions( permissionsIds, folders, auth, ); // Ingest permissions using the ingestService const syncedPermissions = await this.ingestService.ingestData< UnifiedFilestoragePermissionOutput, GoogledrivePermissionOutput >( uniquePermissions, 'googledrive', connectionId, 'filestorage', 'permission', ); // Create a map of original permission ID to synced permission ID const permissionIdMap: Map<string, string> = new Map( syncedPermissions.map((permission) => [ permission.remote_id, permission.id_fs_permission, ]), ); // Update each folder's permissions with the synced permission IDs folders.forEach((folder) => { if (folder.permissionIds?.length) { folder.internal_permissions = folder.permissionIds .map((permissionId) => permissionIdMap.get(permissionId)) .filter( (permissionId): permissionId is string => permissionId !== undefined, ); } }); this.logger.log( `Ingested ${syncedPermissions.length} googledrive permissions for folders.`, ); return folders; } catch (error) { this.logger.error('Error ingesting permissions for folders', error); throw error; } }
/** * Ingests permissions for the provided Google Drive folders into the database. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/googledrive/index.ts#L316-L390
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GoogleDriveFolderService.getFoldersIncremental
private async getFoldersIncremental( auth: OAuth2Client, connectionId: string, ): Promise<GoogleDriveFolderOutput[]> { try { const drive = google.drive({ version: 'v3', auth }); const driveIds = await this.fetchDriveIds(auth); const modifiedFolders = await this.getModifiedFolders( drive, connectionId, ); await this.assignDriveIds(modifiedFolders, auth); return await this.assignParentIds( modifiedFolders, connectionId, driveIds, drive, ); } catch (error) { this.logger.error('Error in incremental folder sync', error); throw error; } }
/** * Retrieves folders that have been modified for each drive using drive's remote_cursor * @param auth OAuth2 client for Google Drive API. * @param connectionId ID of the connection. * @returns Array of Google Drive folders that have been modified. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/googledrive/index.ts#L398-L423
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GoogleDriveFolderService.assignDriveIds
private async assignDriveIds( folders: GoogleDriveFolderOutput[], auth: OAuth2Client, ): Promise<GoogleDriveFolderOutput[]> { const drive = google.drive({ version: 'v3', auth }); const rootDriveId = await this.executeWithRetry(() => drive.files .get({ fileId: 'root', fields: 'id', }) .then((res) => res.data.id), ); folders.forEach((folder) => { folder.driveId = folder.driveId || rootDriveId; }); return folders; }
/** * Assigns driveId as root to folders that don't have one. * @param folders Array of Google Drive folders. * @param auth OAuth2 client for Google Drive API. * @returns Array of Google Drive folders with driveId assigned. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/googledrive/index.ts#L431-L450
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GoogleDriveFolderService.assignParentIds
private async assignParentIds( folders: GoogleDriveFolderOutput[], connectionId: string, driveIds: string[], drive: any, ): Promise<GoogleDriveFolderOutput[]> { const folderIdToInternalIdMap = new Map<string, string>(); const foldersToSync: GoogleDriveFolderOutput[] = []; let remainingFolders = folders; const parentLookupCache = new Map<string, string | null>(); while (remainingFolders.length > 0) { const foldersStillPending = []; for (const folder of remainingFolders) { const parentId = folder.parents?.[0] || 'root'; const internalParentId = await this.resolveParentId( parentId, folderIdToInternalIdMap, driveIds, connectionId, parentLookupCache, ); if (internalParentId) { // Found parent const folder_internal_id = await this.getIntenalIdForFolder( folder.id, connectionId, ); foldersToSync.push( this.createFolderWithInternalIds( folder, internalParentId, folder_internal_id, ), ); folderIdToInternalIdMap.set(folder.id, folder_internal_id); } else { // Could not find parent, try in next iteration foldersStillPending.push(folder); } } if (this.isStuckInLoop(foldersStillPending, remainingFolders)) { const remote_folders = new Map( foldersToSync.map((folder) => [folder.id, folder]), ); await this.handleUnresolvedFolders( foldersStillPending, foldersToSync, remote_folders, parentLookupCache, folderIdToInternalIdMap, driveIds, connectionId, drive, ); break; } remainingFolders = foldersStillPending; } return foldersToSync; }
/** * Assigns parent IDs to folders based on their parents. * Handles circular references and orphaned folders. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/googledrive/index.ts#L456-L521
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
GoogleDriveFolderService.delay
private async delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); }
/** * Delays execution for a specified amount of time. * @param ms Milliseconds to delay. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/googledrive/index.ts#L712-L714
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.ingestPermissionsForFolders
private async ingestPermissionsForFolders( allFolders: OnedriveFolderOutput[], connection: Connection, ): Promise<OnedriveFolderOutput[]> { const allPermissions: OnedrivePermissionOutput[] = []; const folderIdToRemotePermissionIdMap: Map<string, string[]> = new Map(); const batchSize = 4; // simultaneous requests const folders = allFolders.filter((f) => !f.deleted); for (let i = 0; i < folders.length; i += batchSize) { const batch = folders.slice(i, i + batchSize); const permissions = await Promise.all( batch.map(async (folder) => { const permissionConfig: AxiosRequestConfig = { timeout: 30000, method: 'get', url: `${connection.account_url}/v1.0/me/drive/items/${folder.id}/permissions`, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( connection.access_token, )}`, }, }; const resp = await this.makeRequestWithRetry(permissionConfig); const permissions = resp.data.value; folderIdToRemotePermissionIdMap.set( folder.id, permissions.map((p) => p.id), ); return permissions; }), ); allPermissions.push(...permissions.flat()); } const uniquePermissions = Array.from( new Map( allPermissions.map((permission) => [permission.id, permission]), ).values(), ); await this.assignUserAndGroupIdsToPermissions(uniquePermissions); const syncedPermissions = await this.ingestService.ingestData< UnifiedFilestoragePermissionOutput, OnedrivePermissionOutput >( uniquePermissions, 'onedrive', connection.id_connection, 'filestorage', 'permission', ); this.logger.log( `Ingested ${syncedPermissions.length} permissions for folders.`, ); const permissionIdMap: Map<string, string> = new Map( syncedPermissions.map((permission) => [ permission.remote_id, permission.id_fs_permission, ]), ); folders.forEach((folder) => { if (folderIdToRemotePermissionIdMap.has(folder.id)) { folder.internal_permissions = folderIdToRemotePermissionIdMap .get(folder.id) ?.map((permission) => permissionIdMap.get(permission)) .filter((id) => id !== undefined); } }); return allFolders; }
/** * Ingests and assigns permissions for folders. * @param allFolders - Array of OneDriveFolderOutput to process. * @param connection - The connection object. * @returns The updated array of OneDriveFolderOutput with ingested permissions. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L329-L408
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.assignParentIds
private async assignParentIds( folders: OnedriveFolderOutput[], connection: Connection, ): Promise<OnedriveFolderOutput[]> { const folderIdToInternalIdMap: Map<string, string> = new Map(); const foldersToSync: OnedriveFolderOutput[] = []; let remainingFolders: OnedriveFolderOutput[] = [...folders]; const parentLookupCache: Map<string, string | null> = new Map(); while (remainingFolders.length > 0) { const foldersStillPending: OnedriveFolderOutput[] = []; for (const folder of remainingFolders) { const parentId = folder.parentReference?.id || 'root'; const internalParentId = await this.resolveParentId( parentId, folderIdToInternalIdMap, connection.id_connection, parentLookupCache, ); if (internalParentId) { const folder_internal_id = await this.getIntenalIdForFolder( folder.id, connection, ); foldersToSync.push({ ...folder, internal_parent_folder_id: internalParentId === 'root' ? null : internalParentId, internal_id: folder_internal_id, }); folderIdToInternalIdMap.set(folder.id, folder_internal_id); } else { foldersStillPending.push(folder); } } if (foldersStillPending.length === remainingFolders.length) { const remote_folders = new Map( foldersToSync.map((folder) => [folder.id, folder]), ); await this.handleUnresolvedFolders( foldersStillPending, foldersToSync, remote_folders, parentLookupCache, folderIdToInternalIdMap, connection, ); break; } remainingFolders = foldersStillPending; } return foldersToSync; }
/** * Assigns internal parent IDs to OneDrive folders, ensuring proper parent-child relationships. * @param folders - Array of OneDriveFolderOutput to process. * @returns The updated array of OneDriveFolderOutput with assigned internal parent IDs. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L464-L522
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.resolveParentId
private async resolveParentId( parentId: string, idMap: Map<string, string>, connectionId: string, cache: Map<string, string | null>, ): Promise<string | null | undefined> { if (idMap.has(parentId)) { return idMap.get(parentId); } if (parentId === 'root') { return 'root'; } if (cache.has(parentId)) { return cache.get(parentId); } const parentFolder = await this.prisma.fs_folders.findFirst({ where: { remote_id: parentId, id_connection: connectionId, }, select: { id_fs_folder: true }, }); const result = parentFolder?.id_fs_folder || null; cache.set(parentId, result); return result; }
/** * Resolves the internal parent ID for a given remote parent ID. * @param parentId - The remote parent folder ID. * @param idMap - Map of remote IDs to internal IDs. * @param connectionId - The connection ID. * @param cache - Cache for parent ID lookups. * @returns The internal parent ID or null if not found. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L543-L572
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.handleUnresolvedFolders
private async handleUnresolvedFolders( pending: OnedriveFolderOutput[], output: OnedriveFolderOutput[], remote_folders: Map<string, OnedriveFolderOutput>, parentLookupCache: Map<string, string | null>, idCache: Map<string, string | null>, connection: Connection, ): Promise<void> { this.logger.warn( `${pending.length} folders could not be resolved in the initial pass. Attempting to resolve remaining folders.`, ); const getInternalParentRecursive = async ( folder: OnedriveFolderOutput, visitedIds: Set<string> = new Set(), ): Promise<string | null> => { const remote_parent_id = folder.parentReference?.id || 'root'; if (visitedIds.has(remote_parent_id)) { this.logger.warn(`Circular reference detected for folder ${folder.id}`); return null; } visitedIds.add(remote_parent_id); const internal_parent_id = await this.resolveParentId( remote_parent_id, idCache, connection.id_connection, parentLookupCache, ); if (internal_parent_id) { return internal_parent_id; } // Try to get parent from remote folders map or API try { const parentFolder = remote_folders.get(remote_parent_id) || (await this.makeRequestWithRetry({ timeout: 30000, method: 'get', url: `${connection.account_url}/v1.0/me/drive/items/${remote_parent_id}`, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( connection.access_token, )}`, }, })); if (!parentFolder) { return null; } return getInternalParentRecursive( parentFolder as OnedriveFolderOutput, visitedIds, ); } catch (error) { this.logger.error( `Failed to resolve parent for folder ${folder.id}`, error, ); return null; } }; await Promise.all( pending.map(async (folder) => { const internal_parent_id = await getInternalParentRecursive(folder); const folder_internal_id = uuidv4(); idCache.set(folder.id, folder_internal_id); output.push({ ...folder, internal_parent_folder_id: internal_parent_id, internal_id: folder_internal_id, }); }), ); }
/** * Handles folders that couldn't be resolved in the initial pass. * @param pending - Folders still pending resolution. * @param output - Already processed folders. * @param idMap - Map of remote IDs to internal IDs. * @param cache - Cache for parent ID lookups. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L581-L662
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.handleDeletedFolder
async handleDeletedFolder(folderId: string, connection: Connection) { const folder = await this.prisma.fs_folders.findFirst({ where: { id_fs_folder: folderId, id_connection: connection.id_connection, }, select: { remote_was_deleted: true, id_fs_folder: true, parent_folder: true, }, }); if (!folder || folder.remote_was_deleted) { return; } // update the folder to be deleted await this.prisma.fs_folders.update({ where: { id_fs_folder: folderId, }, data: { remote_was_deleted: true, }, }); }
/** * Handles the deletion of a folder by marking it and its children as deleted in the database. * @param folderId - The internal ID of the folder to be marked as deleted. * @param connection - The connection object containing the connection details. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L669-L695
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.folderDeletedOnRemote
private async folderDeletedOnRemote( folder: fs_folders, connection: Connection, ) { try { const remoteFolder = await this.makeRequestWithRetry({ timeout: 30000, method: 'get', url: `${connection.account_url}/v1.0/me/drive/items/${folder.remote_id}?$select=id,deleted`, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( connection.access_token, )}`, }, }); return remoteFolder && remoteFolder.data.deleted; } catch (error: any) { if (error.response?.status === 404) { // If we get a 404, we assume the folder is deleted return true; } throw error; } }
/** * Checks if a folder is deleted on the remote OneDrive service. * @param folder - The folder to check. * @param connection - The connection object containing the connection details. * @returns True if the folder is deleted, false otherwise. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L703-L728
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.getLastSyncTime
private async getLastSyncTime(connectionId: string): Promise<Date | null> { const lastSync = await this.prisma.fs_folders.findFirst({ where: { id_connection: connectionId }, orderBy: { remote_modified_at: { sort: 'desc', nulls: 'last' } }, }); this.logger.log( `Last sync time for connection ${connectionId} one drive folders: ${lastSync?.remote_modified_at}`, ); return lastSync ? lastSync.remote_modified_at : null; }
/** * Gets the last sync time for a connection. * @param connectionId - The ID of the connection. * @returns The last sync time or null if no sync time is found. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L735-L744
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.makeRequestWithRetry
private async makeRequestWithRetry( config: AxiosRequestConfig, ): Promise<AxiosResponse> { let attempts = 0; let backoff: number = this.INITIAL_BACKOFF_MS; while (attempts < this.MAX_RETRIES) { try { const response: AxiosResponse = await axios(config); return response; } catch (error: any) { attempts++; // Handle rate limiting if (error.response && error.response.status === 429) { const retryAfter: number = this.getRetryAfter( error.response.headers['retry-after'], ); const delayTime: number = Math.max(retryAfter * 1000, backoff); this.logger.warn( `Rate limit hit. Retrying request in ${delayTime}ms (Attempt ${attempts}/${this.MAX_RETRIES})`, ); await this.delay(delayTime); backoff *= 2; // Exponential backoff continue; } // Handle timeout errors if ( error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT' || error.response?.code === 'ETIMEDOUT' ) { const delayTime: number = backoff; this.logger.warn( `Request timeout. Retrying in ${delayTime}ms (Attempt ${attempts}/${this.MAX_RETRIES})`, ); await this.delay(delayTime); backoff *= 2; continue; } // Handle server errors (500+) if (error.response && error.response.status >= 500) { const delayTime: number = backoff; this.logger.warn( `Server error ${error.response.status}. Retrying in ${delayTime}ms (Attempt ${attempts}/${this.MAX_RETRIES})`, ); await this.delay(delayTime); backoff *= 2; continue; } // handle 410 gone errors if (error.response?.status === 410 && config.url.includes('delta')) { // todo: handle 410 gone errors } throw error; } } this.logger.error( 'Max retry attempts reached. Request failed.', 'onedrive', 'makeRequestWithRetry', ); throw new Error('Max retry attempts reached.'); }
/** * Makes an HTTP request with rate limit handling using exponential backoff. * @param config - Axios request configuration. * @returns Axios response. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L751-L825
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.getRetryAfter
private getRetryAfter(retryAfterHeader: string | undefined): number { if (!retryAfterHeader) { return 1; // Default to 1 second if header is missing } const retryAfterSeconds: number = parseInt(retryAfterHeader, 10); return isNaN(retryAfterSeconds) ? 1 : retryAfterSeconds + 0.5; }
/** * Parses the Retry-After header to determine the wait time. * @param retryAfterHeader - Value of the Retry-After header. * @returns Retry delay in seconds. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L832-L839
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.delay
private delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); }
/** * Delays execution for the specified duration. * @param ms - Duration in milliseconds. * @returns Promise that resolves after the delay. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/services/onedrive/index.ts#L846-L848
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
SyncService.kickstartSync
async kickstartSync(id_project?: string) { try { const linkedUsers = await this.prisma.linked_users.findMany({ where: { id_project: id_project, }, }); linkedUsers.map(async (linkedUser) => { try { const providers = FILESTORAGE_PROVIDERS; for (const provider of providers) { try { await this.syncForLinkedUser({ integrationId: provider, linkedUserId: linkedUser.id_linked_user, }); } catch (error) { throw error; } } } catch (error) { throw error; } }); } catch (error) { throw error; } }
// every 8 hours
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/folder/sync/sync.service.ts#L41-L68
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.sync
async sync(data: SyncParam): Promise<ApiResponse<OnedriveGroupOutput[]>> { try { const { linkedUserId } = data; const connection = await this.prisma.connections.findFirst({ where: { id_linked_user: linkedUserId, provider_slug: 'onedrive', vertical: 'filestorage', }, }); const config: AxiosRequestConfig = { method: 'get', url: `${connection.account_url}/v1.0/groups`, headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${this.cryptoService.decrypt( connection.access_token, )}`, }, }; const resp: AxiosResponse = await this.makeRequestWithRetry(config); const groups: OnedriveGroupOutput[] = resp.data.value; await this.assignUsersForGroups(groups, connection); this.logger.log(`Synced ${groups.length} OneDrive groups successfully.`); return { data: groups, message: 'OneDrive groups retrieved successfully.', statusCode: 200, }; } catch (error: any) { this.logger.error( `Error syncing OneDrive groups: ${error.message}`, error, ); throw error; } }
/** * Synchronizes OneDrive groups. * @param data - Synchronization parameters. * @returns API response with an array of OneDrive group outputs. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/group/services/onedrive/index.ts#L36-L77
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.makeRequestWithRetry
private async makeRequestWithRetry( config: AxiosRequestConfig, ): Promise<AxiosResponse> { let attempts = 0; let backoff: number = this.INITIAL_BACKOFF_MS; while (attempts < this.MAX_RETRIES) { try { const response: AxiosResponse = await axios(config); return response; } catch (error: any) { attempts++; // Handle rate limiting (429) and server errors (500+) if ( (error.response && error.response.status === 429) || (error.response && error.response.status >= 500) || error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT' || error.response?.code === 'ETIMEDOUT' ) { const retryAfter = this.getRetryAfter( error.response?.headers['retry-after'], ); const delayTime: number = Math.max(retryAfter * 1000, backoff); this.logger.warn( `Request failed with ${ error.code || error.response?.status }. Retrying in ${delayTime}ms (Attempt ${attempts}/${ this.MAX_RETRIES })`, ); await this.delay(delayTime); backoff *= 2; // Exponential backoff continue; } // Handle other errors this.logger.error(`Request failed: ${error.message}`, error); throw error; } } this.logger.error( 'Max retry attempts reached. Request failed.', OnedriveService.name, ); throw new Error('Max retry attempts reached.'); }
/** * Makes an HTTP request with retry logic for handling 500 and 429 errors. * @param config - Axios request configuration. * @returns Axios response. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/group/services/onedrive/index.ts#L136-L186
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.getRetryAfter
private getRetryAfter(retryAfterHeader: string | undefined): number { if (!retryAfterHeader) { return 1; // Default to 1 second if header is missing } const retryAfterSeconds: number = parseInt(retryAfterHeader, 10); return isNaN(retryAfterSeconds) ? 1 : retryAfterSeconds; }
/** * Parses the Retry-After header to determine the wait time. * @param retryAfterHeader - Value of the Retry-After header. * @returns Retry delay in seconds. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/group/services/onedrive/index.ts#L193-L200
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2
Panora
github_2023
panoratech
typescript
OnedriveService.delay
private delay(ms: number): Promise<void> { return new Promise((resolve) => setTimeout(resolve, ms)); }
/** * Delays execution for the specified duration. * @param ms - Duration in milliseconds. * @returns Promise that resolves after the delay. */
https://github.com/panoratech/Panora/blob/c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2/packages/api/src/filestorage/group/services/onedrive/index.ts#L207-L209
c6741e9ef154bf215bcd7a6a4cc51522eae7c7f2