The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Import Teams transcripts when Microsoft Graph notifies that they are ready (#27594)
nitin9d03433dccb8
diff --git a/packages/twenty-apps/public/teams/SETUP.md b/packages/twenty-apps/public/teams/SETUP.mdindex d35d2875329..5382fb5de75 100644--- a/packages/twenty-apps/public/teams/SETUP.md+++ b/packages/twenty-apps/public/teams/SETUP.md@@ -57,7 +57,11 @@ connecting an account does not enable them. With both on, connecting an accountalso creates a Microsoft Graph subscription to the transcripts of the meetingsthat account organizes. Graph delivers its notifications to`https://<your-twenty-host>/webhooks/server/d62e36e1-82bb-4f78-b2ab-54a31faaafab`,-so the Twenty server must be reachable from the internet over HTTPS. A+so the Twenty server must be reachable from the internet over HTTPS. New+transcripts then import automatically into Call Recordings as Microsoft+publishes them. Use the **Sync Teams Transcript** action for transcripts from+before the connection existed, and for any that Microsoft has not published+about two and a half hours after the meeting or whose import keeps failing. Aconnection added while transcripts were off has no subscription: reconnect itafter turning transcripts on. Disconnecting the account or uninstalling the appdeletes the subscription.diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.tsindex e61571d7f7e..438bdac1294 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/universal-identifiers.ts@@ -10,6 +10,9 @@ export const TEAMS_LIST_ORGANIZER_TRANSCRIPTS_UNIVERSAL_IDENTIFIER =export const TEAMS_SYNC_TRANSCRIPT_UNIVERSAL_IDENTIFIER ='c7772775-d871-428f-960e-a43ca365ba22';+export const TEAMS_IMPORT_TRANSCRIPT_UNIVERSAL_IDENTIFIER =+ '374d5e8e-6353-4d75-a4e7-884999a3876b';+export const TEAMS_TRANSCRIPTS_WEBHOOK_RESOLVER_UNIVERSAL_IDENTIFIER ='d62e36e1-82bb-4f78-b2ab-54a31faaafab';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-created-change-type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-created-change-type.tsnew file mode 100644index 00000000000..6143f724fdc--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-created-change-type.ts@@ -0,0 +1 @@+export const GRAPH_CREATED_CHANGE_TYPE = 'created';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-import-job-retry-limit.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-import-job-retry-limit.tsnew file mode 100644index 00000000000..cda291d04fe--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-import-job-retry-limit.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_IMPORT_JOB_RETRY_LIMIT = 3;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-import-retry-delays-milliseconds.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-import-retry-delays-milliseconds.tsnew file mode 100644index 00000000000..463e26cd81c--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-import-retry-delays-milliseconds.ts@@ -0,0 +1,5 @@+export const TEAMS_TRANSCRIPT_IMPORT_RETRY_DELAYS_MILLISECONDS = [+ 5 * 60 * 1_000,+ 30 * 60 * 1_000,+ 2 * 60 * 60 * 1_000,+];diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-import-transcript.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-import-transcript.tsnew file mode 100644index 00000000000..85b848b9cb8--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-import-transcript.ts@@ -0,0 +1,79 @@+import { isNonEmptyString, isPositiveInteger } from '@sniptt/guards';+import { defineLogicFunction } from 'twenty-sdk/define';+import { kv } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { FEATURE_FLAGS } from 'src/constants/feature-flags';+import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';+import { TEAMS_IMPORT_TRANSCRIPT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import { type TeamsTranscriptImportOutcome } from 'src/features/transcripts/logic-functions/types/teams-transcript-import-outcome.type';+import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';+import { buildTeamsTranscriptSubscriptionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key';+import { importTeamsTranscriptOrScheduleRetry } from 'src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry';+import { isFeatureEnabled } from 'src/utils/is-feature-enabled';++type TeamsImportTranscriptResult =+ | { success: true; outcome: TeamsTranscriptImportOutcome }+ | { success: true; skipped: true; reason: string }+ | { success: false; error: string };++export const teamsImportTranscriptHandler = async (payload: {+ connectedAccountId?: unknown;+ meetingId?: unknown;+ transcriptId?: unknown;+ attempt?: unknown;+}): Promise<TeamsImportTranscriptResult> => {+ const { connectedAccountId, meetingId, transcriptId, attempt } = payload;++ if (+ !isNonEmptyString(connectedAccountId) ||+ !isNonEmptyString(meetingId) ||+ !isNonEmptyString(transcriptId) ||+ !isPositiveInteger(attempt)+ ) {+ return { success: false, error: 'Invalid Teams transcript import job' };+ }++ if (+ !isFeatureEnabled({+ isAvailable: FEATURE_FLAGS.IS_TRANSCRIPT_IMPORT_ENABLED,+ settingValue: process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY],+ })+ ) {+ return {+ success: true,+ skipped: true,+ reason: 'Teams transcripts are not enabled',+ };+ }++ const subscription = await kv.get<TeamsTranscriptSubscription>(+ buildTeamsTranscriptSubscriptionKvKey(connectedAccountId),+ );++ if (!isDefined(subscription)) {+ return {+ success: true,+ skipped: true,+ reason: 'Teams connection no longer has a transcript subscription',+ };+ }++ const { outcome } = await importTeamsTranscriptOrScheduleRetry({+ connectedAccountId,+ meetingId,+ transcriptId,+ attempt,+ });++ return { success: true, outcome };+};++export default defineLogicFunction({+ universalIdentifier: TEAMS_IMPORT_TRANSCRIPT_UNIVERSAL_IDENTIFIER,+ name: 'teams-import-transcript',+ description:+ 'Retries importing a Teams transcript that Microsoft had not published when its notification arrived.',+ timeoutSeconds: 300,+ handler: teamsImportTranscriptHandler,+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.tsindex 1f6d49b1571..b60afd6c5cd 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-sync-transcript.ts@@ -10,6 +10,7 @@ import {import { FEATURE_FLAGS } from 'src/constants/feature-flags';import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';import { TEAMS_SYNC_TRANSCRIPT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import { type CallRecordingSyncFields } from 'src/features/transcripts/logic-functions/types/call-recording-sync-fields.type';import { getTeamsConnectionForRequestOrThrow } from 'src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw';import { syncTeamsTranscriptToCallRecordingOrThrow } from 'src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw';import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';@@ -38,6 +39,7 @@ type TeamsSyncTranscriptResult =success: true;callRecordingId: string;calendarEventId?: string;+ status: CallRecordingSyncFields['status'];created: boolean;skipped: boolean;}@@ -102,6 +104,7 @@ export default defineLogicFunction({error: { type: 'string' },callRecordingId: { type: 'string' },calendarEventId: { type: 'string' },+ status: { type: 'string' },created: { type: 'boolean' },skipped: { type: 'boolean' },},diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.tsindex 725f162d814..80b322ef02d 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcripts-webhook.ts@@ -1,24 +1,85 @@import { isNonEmptyString } from '@sniptt/guards';import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';-import { getConnection, kv } from 'twenty-sdk/logic-function';+import {+ getConnection,+ kv,+ RetryableLogicFunctionError,+} from 'twenty-sdk/logic-function';import { isDefined } from 'twenty-sdk/utils';import { FEATURE_FLAGS } from 'src/constants/feature-flags';import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';import { TEAMS_TRANSCRIPTS_WEBHOOK_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import { GRAPH_CREATED_CHANGE_TYPE } from 'src/features/transcripts/logic-functions/constants/graph-created-change-type';import { GRAPH_REAUTHORIZATION_REQUIRED_LIFECYCLE_EVENT } from 'src/features/transcripts/logic-functions/constants/graph-reauthorization-required-lifecycle-event';import { TEAMS_TRANSCRIPTS_WEBHOOK_CONNECTION_QUERY_PARAMETER } from 'src/features/transcripts/logic-functions/constants/teams-transcripts-webhook-connection-query-parameter';+import { type TeamsTranscriptImportOutcome } from 'src/features/transcripts/logic-functions/types/teams-transcript-import-outcome.type';import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';import { buildTeamsTranscriptSubscriptionKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-subscription-kv-key';+import { importTeamsTranscriptOrScheduleRetry } from 'src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry';+import { parseTeamsTranscriptResource } from 'src/features/transcripts/logic-functions/utils/parse-teams-transcript-resource';import { parseTeamsTranscriptSubscriptionNotifications } from 'src/features/transcripts/logic-functions/utils/parse-teams-transcript-subscription-notifications';import { renewTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/renew-teams-transcript-subscription';+import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';import { isFeatureEnabled } from 'src/utils/is-feature-enabled';type TeamsTranscriptsWebhookResult =- | { success: true; expirationDateTime?: string }+ | {+ success: true;+ expirationDateTime?: string;+ transcriptImportOutcomes: TeamsTranscriptImportOutcome[];+ }| { success: true; skipped: true; reason: string }| { success: false; error: string };+const renewStoredTeamsTranscriptSubscription = async ({+ connectedAccountId,+ subscriptionKvKey,+ subscription,+}: {+ connectedAccountId: string;+ subscriptionKvKey: string;+ subscription: TeamsTranscriptSubscription;+}): Promise<string> => {+ const { accessToken } = await getConnection(connectedAccountId);+ const expirationDateTime = await renewTeamsTranscriptSubscription({+ accessToken,+ subscriptionId: subscription.subscriptionId,+ });++ await kv.set(subscriptionKvKey, { ...subscription, expirationDateTime });++ return expirationDateTime;+};++const isRetryableRejection = (+ settledResult: PromiseSettledResult<unknown>,+): settledResult is PromiseRejectedResult =>+ settledResult.status === 'rejected' &&+ settledResult.reason instanceof RetryableLogicFunctionError;++const importTeamsTranscriptFromResourceOrThrow = async ({+ connectedAccountId,+ resource,+}: {+ connectedAccountId: string;+ resource: unknown;+}): Promise<TeamsTranscriptImportOutcome> => {+ const transcriptReference = parseTeamsTranscriptResource(resource);++ if (!isDefined(transcriptReference)) {+ throw new Error('Microsoft Graph sent an unrecognized transcript resource');+ }++ const { outcome } = await importTeamsTranscriptOrScheduleRetry({+ connectedAccountId,+ ...transcriptReference,+ attempt: 0,+ });++ return outcome;+};+export const teamsTranscriptsWebhookHandler = async (routePayload: RoutePayload<unknown>,): Promise<TeamsTranscriptsWebhookResult> => {@@ -49,16 +110,6 @@ export const teamsTranscriptsWebhookHandler = async (return { success: false, error: 'Invalid Microsoft Graph notification' };}- const isReauthorizationRequired = notifications.some(- (notification) =>- notification.lifecycleEvent ===- GRAPH_REAUTHORIZATION_REQUIRED_LIFECYCLE_EVENT,- );-- if (!isReauthorizationRequired) {- return { success: true };- }-if (!isFeatureEnabled({isAvailable: FEATURE_FLAGS.IS_TRANSCRIPT_IMPORT_ENABLED,@@ -72,22 +123,74 @@ export const teamsTranscriptsWebhookHandler = async (};}- const { accessToken } = await getConnection(connectedAccountId);- const expirationDateTime = await renewTeamsTranscriptSubscription({- accessToken,- subscriptionId: subscription.subscriptionId,- });+ const isReauthorizationRequired = notifications.some(+ (notification) =>+ notification.lifecycleEvent ===+ GRAPH_REAUTHORIZATION_REQUIRED_LIFECYCLE_EVENT,+ );+ const transcriptResources = notifications+ .filter(+ (notification) => notification.changeType === GRAPH_CREATED_CHANGE_TYPE,+ )+ .map((notification) => notification.resource);+ const [subscriptionRenewal, ...transcriptImports] = await Promise.allSettled([+ isReauthorizationRequired+ ? renewStoredTeamsTranscriptSubscription({+ connectedAccountId,+ subscriptionKvKey,+ subscription,+ })+ : undefined,+ ...transcriptResources.map((resource) =>+ importTeamsTranscriptFromResourceOrThrow({+ connectedAccountId,+ resource,+ }),+ ),+ ]);+ const transcriptImportOutcomes = transcriptImports.map(+ (transcriptImport, index): TeamsTranscriptImportOutcome => {+ if (transcriptImport.status === 'fulfilled') {+ return transcriptImport.value;+ }- await kv.set(subscriptionKvKey, { ...subscription, expirationDateTime });+ console.error(+ `[teams] failed to import transcript ${String(transcriptResources[index])} for connected account ${connectedAccountId}: ${toErrorMessage(transcriptImport.reason)}`,+ );++ return 'failed';+ },+ );++ const retryableTranscriptImport =+ transcriptImports.find(isRetryableRejection);++ if (subscriptionRenewal.status === 'rejected') {+ console.error(+ `[teams] failed to renew transcript subscription ${subscription.subscriptionId} for connected account ${connectedAccountId}: ${toErrorMessage(subscriptionRenewal.reason)}`,+ );+ }++ if (isDefined(retryableTranscriptImport)) {+ throw retryableTranscriptImport.reason;+ }++ if (subscriptionRenewal.status === 'rejected') {+ throw subscriptionRenewal.reason;+ }- return { success: true, expirationDateTime };+ return {+ success: true,+ expirationDateTime: subscriptionRenewal.value,+ transcriptImportOutcomes,+ };};export default defineLogicFunction({universalIdentifier: TEAMS_TRANSCRIPTS_WEBHOOK_UNIVERSAL_IDENTIFIER,name: 'teams-transcripts-webhook',description:- 'Checks Microsoft Graph transcript notifications against the subscription stored for the connection, and renews the subscription when Graph asks for reauthorization.',- timeoutSeconds: 60,+ 'Checks Microsoft Graph transcript notifications against the subscription stored for the connection, imports new transcripts into Call Recordings, and renews the subscription when Graph asks for reauthorization.',+ timeoutSeconds: 900,handler: teamsTranscriptsWebhookHandler,});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-import-outcome.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-import-outcome.type.tsnew file mode 100644index 00000000000..148c2fe8887--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-import-outcome.type.ts@@ -0,0 +1,6 @@+export type TeamsTranscriptImportOutcome =+ | 'imported'+ | 'skipped-deleted'+ | 'retry-scheduled'+ | 'retries-exhausted'+ | 'failed';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-teams-transcript-resource.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-teams-transcript-resource.test.tsnew file mode 100644index 00000000000..1300924c11f--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/parse-teams-transcript-resource.test.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from 'vitest';++import { parseTeamsTranscriptResource } from 'src/features/transcripts/logic-functions/utils/parse-teams-transcript-resource';++const ORGANIZER_ID = '976f4b31-fd01-4e0b-9178-29cc40c14438';++const MEETING_ID =+ 'MSo5NzZmNGIzMS1mZDAxLTRlMGItOTE3OC0yOWNjNDBjMTQ0MzgqMCoqMTk6bWVldGluZ19ZMlE=';++const TRANSCRIPT_ID =+ 'MSMjMCMjNzU3ODc2ZDYtOTcwMi00MDhkLWFkNDItOTE2ZDNmZjkwZGY4';++describe('parseTeamsTranscriptResource', () => {+ it('should read the ids from the resource Graph sends for transcripts', () => {+ expect(+ parseTeamsTranscriptResource(+ `users/${ORGANIZER_ID}/onlineMeetings('${MEETING_ID}')/transcripts('${TRANSCRIPT_ID}')`,+ ),+ ).toEqual({ meetingId: MEETING_ID, transcriptId: TRANSCRIPT_ID });+ });++ it('should read the ids when the user id is quoted or the path starts with a slash', () => {+ expect(+ parseTeamsTranscriptResource(+ `users('${ORGANIZER_ID}')/onlineMeetings('${MEETING_ID}')/transcripts('${TRANSCRIPT_ID}')`,+ ),+ ).toEqual({ meetingId: MEETING_ID, transcriptId: TRANSCRIPT_ID });+ expect(+ parseTeamsTranscriptResource(+ `/users/${ORGANIZER_ID}/onlineMeetings('${MEETING_ID}')/transcripts('${TRANSCRIPT_ID}')`,+ ),+ ).toEqual({ meetingId: MEETING_ID, transcriptId: TRANSCRIPT_ID });+ });++ it('should decode the ids of a slash-delimited resource', () => {+ expect(+ parseTeamsTranscriptResource(+ `/users/${ORGANIZER_ID}/onlineMeetings/meeting%2Fone%3D/transcripts/transcript%2Fone%3D`,+ ),+ ).toEqual({ meetingId: 'meeting/one=', transcriptId: 'transcript/one=' });+ });++ it.each([+ undefined,+ '',+ 'https://graph.microsoft.com/v1.0/users/organizer/onlineMeetings/m/transcripts/t',+ `users/${ORGANIZER_ID}/onlineMeetings/getAllTranscripts`,+ "users/organizer/onlineMeetings('m')/transcripts('t')/content",+ 'users/organizer/onlineMeetings/m/transcripts/t/content',+ "users/organizer/onlineMeetings('m')/recordings('r')",+ "users/organizer/onlineMeetings('m')/transcripts('%invalid')",+ 'users/organizer/onlineMeetings/m/transcripts/%invalid',+ ])('should reject %s', (resource) => {+ expect(parseTeamsTranscriptResource(resource)).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription.tsindex 0f094c3a595..868eec64536 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription.ts@@ -1,6 +1,7 @@import { randomBytes } from 'node:crypto';import { isNonEmptyString } from '@sniptt/guards';+import { GRAPH_CREATED_CHANGE_TYPE } from 'src/features/transcripts/logic-functions/constants/graph-created-change-type';import { TEAMS_TRANSCRIPT_SUBSCRIPTION_LIFETIME_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-subscription-lifetime-milliseconds';import { type GraphSubscription } from 'src/features/transcripts/logic-functions/types/graph-subscription.type';import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';@@ -28,7 +29,7 @@ export const createTeamsTranscriptSubscription = async ({url: 'subscriptions',method: 'POST',body: {- changeType: 'created',+ changeType: GRAPH_CREATED_CHANGE_TYPE,notificationUrl,lifecycleNotificationUrl: notificationUrl,resource: `users/${user.id}/onlineMeetings/getAllTranscripts`,diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw.tsnew file mode 100644index 00000000000..2233c38e450--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw.ts@@ -0,0 +1,43 @@+import {+ enqueueJobs,+ RetryableLogicFunctionError,+} from 'twenty-sdk/logic-function';++import { TEAMS_IMPORT_TRANSCRIPT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import { TEAMS_TRANSCRIPT_IMPORT_JOB_RETRY_LIMIT } from 'src/features/transcripts/logic-functions/constants/teams-transcript-import-job-retry-limit';+import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';+import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';++export const enqueueTeamsTranscriptImportRetryOrThrow = async ({+ connectedAccountId,+ meetingId,+ transcriptId,+ attempt,+ delayMilliseconds,+}: {+ connectedAccountId: string;+ meetingId: string;+ transcriptId: string;+ attempt: number;+ delayMilliseconds: number;+}): Promise<void> => {+ try {+ await enqueueJobs({+ logicFunctionUniversalIdentifier:+ TEAMS_IMPORT_TRANSCRIPT_UNIVERSAL_IDENTIFIER,+ jobs: [+ {+ // Graph transcript ids hold characters that job ids reject.+ jobId: `teams-transcript-import-${computeCallRecordingIdForTeamsTranscript(transcriptId)}-${attempt}`,+ payload: { connectedAccountId, meetingId, transcriptId, attempt },+ },+ ],+ retryLimit: TEAMS_TRANSCRIPT_IMPORT_JOB_RETRY_LIMIT,+ delayMs: delayMilliseconds,+ });+ } catch (error) {+ throw new RetryableLogicFunctionError(+ `Could not schedule the next import of Teams transcript ${transcriptId}: ${toErrorMessage(error)}`,+ );+ }+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry.tsnew file mode 100644index 00000000000..82e1fe87a5d--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-or-schedule-retry.ts@@ -0,0 +1,111 @@+import { CoreApiClient } from 'twenty-client-sdk/core';+import {+ AppConnectionAuthFailedError,+ getConnection,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { TEAMS_TRANSCRIPT_IMPORT_RETRY_DELAYS_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-import-retry-delays-milliseconds';+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { type TeamsTranscriptImportOutcome } from 'src/features/transcripts/logic-functions/types/teams-transcript-import-outcome.type';+import { enqueueTeamsTranscriptImportRetryOrThrow } from 'src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-import-retry-or-throw';+import { syncTeamsTranscriptToCallRecordingOrThrow } from 'src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw';+import { toErrorMessage } from 'src/features/transcripts/logic-functions/utils/to-error-message';++type TeamsTranscriptSyncAttempt =+ | { outcome: 'imported' | 'skipped-deleted' | 'failed' }+ | { outcome: 'retry-needed'; retryReason: string };++const isPermanentTeamsTranscriptImportError = (error: unknown): boolean =>+ error instanceof AppConnectionAuthFailedError ||+ (error instanceof GraphRequestError &&+ (error.status === 401 || error.status === 403));++const attemptTeamsTranscriptSync = async ({+ connectedAccountId,+ meetingId,+ transcriptId,+}: {+ connectedAccountId: string;+ meetingId: string;+ transcriptId: string;+}): Promise<TeamsTranscriptSyncAttempt> => {+ try {+ const { accessToken } = await getConnection(connectedAccountId);+ const syncResult = await syncTeamsTranscriptToCallRecordingOrThrow({+ accessToken,+ coreApiClient: new CoreApiClient({ runAs: 'application' }),+ meetingId,+ transcriptId,+ });++ if (syncResult.skipped) {+ return { outcome: 'skipped-deleted' };+ }++ return syncResult.status === 'COMPLETED'+ ? { outcome: 'imported' }+ : {+ outcome: 'retry-needed',+ retryReason: 'Microsoft is still processing the transcript',+ };+ } catch (error) {+ if (error instanceof GraphRequestError && error.status === 404) {+ return {+ outcome: 'retry-needed',+ retryReason: 'Microsoft Graph did not find the transcript',+ };+ }++ console.error(+ `[teams] failed to import transcript ${transcriptId} for connected account ${connectedAccountId}: ${toErrorMessage(error)}`,+ );++ return isPermanentTeamsTranscriptImportError(error)+ ? { outcome: 'failed' }+ : { outcome: 'retry-needed', retryReason: toErrorMessage(error) };+ }+};++export const importTeamsTranscriptOrScheduleRetry = async ({+ connectedAccountId,+ meetingId,+ transcriptId,+ attempt,+}: {+ connectedAccountId: string;+ meetingId: string;+ transcriptId: string;+ attempt: number;+}): Promise<{ outcome: TeamsTranscriptImportOutcome }> => {+ const syncAttempt = await attemptTeamsTranscriptSync({+ connectedAccountId,+ meetingId,+ transcriptId,+ });++ if (syncAttempt.outcome !== 'retry-needed') {+ return { outcome: syncAttempt.outcome };+ }++ const retryDelayMilliseconds =+ TEAMS_TRANSCRIPT_IMPORT_RETRY_DELAYS_MILLISECONDS[attempt];++ if (!isDefined(retryDelayMilliseconds)) {+ console.error(+ `[teams] gave up importing transcript ${transcriptId} for connected account ${connectedAccountId}: ${syncAttempt.retryReason}. The Sync Teams Transcript action can import it.`,+ );++ return { outcome: 'retries-exhausted' };+ }++ await enqueueTeamsTranscriptImportRetryOrThrow({+ connectedAccountId,+ meetingId,+ transcriptId,+ attempt: attempt + 1,+ delayMilliseconds: retryDelayMilliseconds,+ });++ return { outcome: 'retry-scheduled' };+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-teams-transcript-resource.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-teams-transcript-resource.tsnew file mode 100644index 00000000000..bbd6e7a64a1--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/parse-teams-transcript-resource.ts@@ -0,0 +1,36 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isDefined } from 'twenty-sdk/utils';++export const parseTeamsTranscriptResource = (+ resource: unknown,+): { meetingId: string; transcriptId: string } | undefined => {+ if (!isNonEmptyString(resource)) {+ return undefined;+ }++ const match =+ /^\/?users\/[^/]+\/onlineMeetings\('([^']+)'\)\/transcripts\('([^']+)'\)$/.exec(+ resource,+ ) ??+ /^\/?users\('[^']+'\)\/onlineMeetings\('([^']+)'\)\/transcripts\('([^']+)'\)$/.exec(+ resource,+ ) ??+ /^\/?users\/[^/]+\/onlineMeetings\/([^/]+)\/transcripts\/([^/]+)$/.exec(+ resource,+ );++ if (!isDefined(match)) {+ return undefined;+ }++ const [, encodedMeetingId, encodedTranscriptId] = match;++ try {+ return {+ meetingId: decodeURIComponent(encodedMeetingId),+ transcriptId: decodeURIComponent(encodedTranscriptId),+ };+ } catch {+ return undefined;+ }+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.tsindex 66c9cf131dd..dfe432bf2d5 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts@@ -1,5 +1,6 @@import { type CoreApiClient } from 'twenty-client-sdk/core';+import { type CallRecordingSyncFields } from 'src/features/transcripts/logic-functions/types/call-recording-sync-fields.type';import { buildTeamsCallRecordingSyncFields } from 'src/features/transcripts/logic-functions/utils/build-teams-call-recording-sync-fields';import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';import { fetchTeamsTranscriptData } from 'src/features/transcripts/logic-functions/utils/fetch-teams-transcript-data';@@ -20,6 +21,7 @@ export const syncTeamsTranscriptToCallRecordingOrThrow = async ({}): Promise<{callRecordingId: string;calendarEventId?: string;+ status: CallRecordingSyncFields['status'];created: boolean;skipped: boolean;}> => {@@ -46,5 +48,5 @@ export const syncTeamsTranscriptToCallRecordingOrThrow = async ({fields,});- return { callRecordingId, calendarEventId, ...result };+ return { callRecordingId, calendarEventId, status: fields.status, ...result };};