The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Import the last 31 days of Teams transcripts when an account connects (#27677)
nitinc6590349e541
diff --git a/packages/twenty-apps/public/teams/SETUP.md b/packages/twenty-apps/public/teams/SETUP.mdindex a066a260901..54cb469a551 100644--- a/packages/twenty-apps/public/teams/SETUP.md+++ b/packages/twenty-apps/public/teams/SETUP.md@@ -59,12 +59,15 @@ that 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. Newtranscripts 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. A-connection added while transcripts were off has no subscription: reconnect it-after turning transcripts on. Disconnecting the account or uninstalling the app-deletes the subscription.+publishes them. A connection added while transcripts were off has no+subscription: reconnect it after turning transcripts on. Disconnecting the+account or uninstalling the app deletes the subscription.++Connecting also imports the transcripts of the last 31 days, once per+connection. Reconnecting starts it again only when that import failed or+stalled. Use the **Sync Teams Transcript** action for older transcripts, and+for any that Microsoft had not published about two and a half hours after the+meeting or whose import keeps failing.Transcripts link to the meeting's calendar event when that calendar is synced inTwenty. An occurrence of a recurring meeting links to the series' event.diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-register-connection.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-register-connection.tsindex 5c0a9f91690..52444e0c22c 100644--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-register-connection.ts+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-register-connection.ts@@ -3,13 +3,19 @@ import { defineLogicFunction } from 'twenty-sdk/define';import { TEAMS_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER } from 'src/features/chat/constants/universal-identifiers';import { registerTeamsConnection } from 'src/features/chat/logic-functions/utils/register-teams-connection';import { registerTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription';+import { startTeamsTranscriptHistoryInitialImportOrThrow } from 'src/features/transcripts/logic-functions/utils/start-teams-transcript-history-initial-import-or-throw';export const teamsRegisterConnectionHandler = async (payload: {connectedAccountId: string;}) => {- const [chatRegistration, transcriptRegistration] = await Promise.allSettled([+ const [+ chatRegistration,+ transcriptRegistration,+ transcriptHistoryInitialImport,+ ] = await Promise.allSettled([registerTeamsConnection(payload),registerTeamsTranscriptSubscription(payload),+ startTeamsTranscriptHistoryInitialImportOrThrow(payload),]);if (chatRegistration.status === 'rejected') {@@ -20,6 +26,10 @@ export const teamsRegisterConnectionHandler = async (payload: {throw transcriptRegistration.reason;}+ if (transcriptHistoryInitialImport.status === 'rejected') {+ throw transcriptHistoryInitialImport.reason;+ }+return { ...chatRegistration.value, ...transcriptRegistration.value };};@@ -27,7 +37,7 @@ export default defineLogicFunction({universalIdentifier: TEAMS_REGISTER_CONNECTION_UNIVERSAL_IDENTIFIER,name: 'teams-register-connection',description:- 'Runs when a Microsoft Teams connection is added. For a workspace-shared connection with chat enabled, reads the Microsoft tenant id from Graph and claims it for this workspace under the server-scoped teams-tenant:<tenant_id> key, so activities from that tenant route here. Personal connections are left alone. With transcripts enabled, also subscribes to the transcripts of the meetings the account organizes, so Microsoft Graph notifies the app when one is ready.',+ 'Runs when a Microsoft Teams connection is added. For a workspace-shared connection with chat enabled, reads the Microsoft tenant id from Graph and claims it for this workspace under the server-scoped teams-tenant:<tenant_id> key, so activities from that tenant route here. Personal connections are left alone. With transcripts enabled, also subscribes to the transcripts of the meetings the account organizes, so Microsoft Graph notifies the app when one is ready, and starts importing the last 31 days of transcripts once per connection, again on a reconnect when that import failed or stalled.',timeoutSeconds: 30,handler: teamsRegisterConnectionHandler,});diff --git a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-tenant-release.ts b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-tenant-release.tsindex f9a4ee40cc9..ca5f2ee56cb 100644--- a/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-tenant-release.ts+++ b/packages/twenty-apps/public/teams/src/features/chat/logic-functions/teams-tenant-release.ts@@ -2,15 +2,18 @@ import { defineLogicFunction } from 'twenty-sdk/define';import { TEAMS_TENANT_RELEASE_UNIVERSAL_IDENTIFIER } from 'src/features/chat/constants/universal-identifiers';import { releaseTeamsConnectionTenant } from 'src/features/chat/logic-functions/utils/release-teams-connection-tenant';+import { deleteTeamsTranscriptHistoryKvKeys } from 'src/features/transcripts/logic-functions/utils/delete-teams-transcript-history-kv-keys';import { unregisterTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription';export const teamsTenantReleaseHandler = async (payload: {connectedAccountId: string;}) => {- const [tenantRelease, transcriptUnregistration] = await Promise.allSettled([- releaseTeamsConnectionTenant(payload),- unregisterTeamsTranscriptSubscription(payload),- ]);+ const [tenantRelease, transcriptUnregistration, transcriptHistoryDeletion] =+ await Promise.allSettled([+ releaseTeamsConnectionTenant(payload),+ unregisterTeamsTranscriptSubscription(payload),+ deleteTeamsTranscriptHistoryKvKeys(payload),+ ]);if (tenantRelease.status === 'rejected') {throw tenantRelease.reason;@@ -20,6 +23,10 @@ export const teamsTenantReleaseHandler = async (payload: {throw transcriptUnregistration.reason;}+ if (transcriptHistoryDeletion.status === 'rejected') {+ throw transcriptHistoryDeletion.reason;+ }+return { ...tenantRelease.value, ...transcriptUnregistration.value };};@@ -27,7 +34,7 @@ export default defineLogicFunction({universalIdentifier: TEAMS_TENANT_RELEASE_UNIVERSAL_IDENTIFIER,name: 'teams-tenant-release',description:- 'Runs when a Microsoft Teams connection is removed. Releases the teams-tenant:<tenant_id> claim that connection took, unless another connection in this workspace still holds the same tenant, so another workspace can connect it. Also deletes the Microsoft Graph transcript subscription of that connection.',+ 'Runs when a Microsoft Teams connection is removed. Releases the teams-tenant:<tenant_id> claim that connection took, unless another connection in this workspace still holds the same tenant, so another workspace can connect it. Also deletes the Microsoft Graph transcript subscription and the transcript history import state of that connection.',timeoutSeconds: 30,handler: teamsTenantReleaseHandler,});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-import-page-delay-milliseconds.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-import-page-delay-milliseconds.tsnew file mode 100644index 00000000000..e3568bc371c--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-import-page-delay-milliseconds.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_HISTORY_IMPORT_PAGE_DELAY_MILLISECONDS = 60_000;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-initial-import-days.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-initial-import-days.tsnew file mode 100644index 00000000000..4285ba52898--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-initial-import-days.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_HISTORY_INITIAL_IMPORT_DAYS = 31;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 438bdac1294..9e97d23a655 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@@ -21,3 +21,6 @@ export const TEAMS_TRANSCRIPTS_WEBHOOK_UNIVERSAL_IDENTIFIER =export const TEAMS_UNINSTALL_UNIVERSAL_IDENTIFIER ='962da060-1263-4892-9bf5-2b0637818de9';++export const TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER =+ 'ff766fbb-0c55-45db-97ee-590aeb5b87a6';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-access-to-transcripts-disabled-error-code.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-access-to-transcripts-disabled-error-code.tsnew file mode 100644index 00000000000..986aad376c6--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/graph-access-to-transcripts-disabled-error-code.ts@@ -0,0 +1,2 @@+export const GRAPH_ACCESS_TO_TRANSCRIPTS_DISABLED_ERROR_CODE =+ 'GraphAccessToTranscriptsDisabled';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/milliseconds-per-day.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/milliseconds-per-day.tsnew file mode 100644index 00000000000..676b82d25cb--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/milliseconds-per-day.ts@@ -0,0 +1 @@+export const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1_000;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-import-transcript-history-timeout-seconds.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-import-transcript-history-timeout-seconds.tsnew file mode 100644index 00000000000..fa196c49d7a--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-import-transcript-history-timeout-seconds.ts@@ -0,0 +1 @@+export const TEAMS_IMPORT_TRANSCRIPT_HISTORY_TIMEOUT_SECONDS = 900;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-kv-key-prefix.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-kv-key-prefix.tsnew file mode 100644index 00000000000..fce6bf5fe47--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-kv-key-prefix.ts@@ -0,0 +1,2 @@+export const TEAMS_TRANSCRIPT_HISTORY_KV_KEY_PREFIX =+ 'teams-transcript-history';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-retry-delays-milliseconds.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-retry-delays-milliseconds.tsnew file mode 100644index 00000000000..33e8963cdf6--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-retry-delays-milliseconds.ts@@ -0,0 +1,5 @@+export const TEAMS_TRANSCRIPT_HISTORY_RETRY_DELAYS_MILLISECONDS = [+ 60 * 1_000,+ 5 * 60 * 1_000,+ 10 * 60 * 1_000,+];diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-stall-margin-milliseconds.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-stall-margin-milliseconds.tsnew file mode 100644index 00000000000..230b3980330--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-stall-margin-milliseconds.ts@@ -0,0 +1,2 @@+export const TEAMS_TRANSCRIPT_HISTORY_STALL_MARGIN_MILLISECONDS =+ 15 * 60 * 1_000;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-stall-threshold-milliseconds.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-stall-threshold-milliseconds.tsnew file mode 100644index 00000000000..c929f72ed13--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-stall-threshold-milliseconds.ts@@ -0,0 +1,8 @@+import { TEAMS_IMPORT_TRANSCRIPT_HISTORY_TIMEOUT_SECONDS } from 'src/features/transcripts/logic-functions/constants/teams-import-transcript-history-timeout-seconds';+import { TEAMS_TRANSCRIPT_HISTORY_RETRY_DELAYS_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-retry-delays-milliseconds';+import { TEAMS_TRANSCRIPT_HISTORY_STALL_MARGIN_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-stall-margin-milliseconds';++export const TEAMS_TRANSCRIPT_HISTORY_STALL_THRESHOLD_MILLISECONDS =+ Math.max(...TEAMS_TRANSCRIPT_HISTORY_RETRY_DELAYS_MILLISECONDS) ++ TEAMS_IMPORT_TRANSCRIPT_HISTORY_TIMEOUT_SECONDS * 1_000 ++ TEAMS_TRANSCRIPT_HISTORY_STALL_MARGIN_MILLISECONDS;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-upsert-batch-size.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-upsert-batch-size.tsnew file mode 100644index 00000000000..5bd32b245c0--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-upsert-batch-size.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_HISTORY_UPSERT_BATCH_SIZE = 10;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-import-transcript-history.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-import-transcript-history.tsnew file mode 100644index 00000000000..8d48bbe0401--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-import-transcript-history.ts@@ -0,0 +1,19 @@+import { defineLogicFunction } from 'twenty-sdk/define';++import { TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import { TEAMS_IMPORT_TRANSCRIPT_HISTORY_TIMEOUT_SECONDS } from 'src/features/transcripts/logic-functions/constants/teams-import-transcript-history-timeout-seconds';+import { type TeamsTranscriptHistoryJobPayload } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type';+import { processTeamsTranscriptHistoryPageOrThrow } from 'src/features/transcripts/logic-functions/utils/process-teams-transcript-history-page-or-throw';++export const teamsImportTranscriptHistoryHandler = (+ payload: Partial<Record<keyof TeamsTranscriptHistoryJobPayload, unknown>>,+) => processTeamsTranscriptHistoryPageOrThrow(payload);++export default defineLogicFunction({+ universalIdentifier: TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER,+ name: 'teams-import-transcript-history',+ description:+ 'Imports the Teams transcripts on one calendar page of a history import window into Call Recordings, skipping recordings that are complete or deleted in Twenty, then queues the next page a minute later.',+ timeoutSeconds: TEAMS_IMPORT_TRANSCRIPT_HISTORY_TIMEOUT_SECONDS,+ handler: teamsImportTranscriptHistoryHandler,+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-list-organizer-transcripts.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-list-organizer-transcripts.tsindex 41beedba8a5..94f33926cef 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-list-organizer-transcripts.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-list-organizer-transcripts.ts@@ -1,6 +1,5 @@import { isNonEmptyString } from '@sniptt/guards';import { defineLogicFunction } from 'twenty-sdk/define';-import { isDefined } from 'twenty-sdk/utils';import {type InputJsonSchema,type LogicFunctionExecutionContext,@@ -11,11 +10,9 @@ 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_LIST_ORGANIZER_TRANSCRIPTS_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';import { buildTeamsCalendarViewUrl } from 'src/features/transcripts/logic-functions/utils/build-teams-calendar-view-url';-import { getMeetingByJoinUrl } from 'src/features/transcripts/logic-functions/utils/get-meeting-by-join-url';import { getTeamsConnectionForRequestOrThrow } from 'src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw';-import { isTranscriptDuringOccurrence } from 'src/features/transcripts/logic-functions/utils/is-transcript-during-occurrence';-import { listMeetingTranscripts } from 'src/features/transcripts/logic-functions/utils/list-meeting-transcripts';import { listTeamsCalendarPage } from 'src/features/transcripts/logic-functions/utils/list-teams-calendar-page';+import { listTeamsOccurrenceTranscripts } from 'src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts';import { resolveTeamsCalendarNextPageUrlOrThrow } from 'src/features/transcripts/logic-functions/utils/resolve-teams-calendar-next-page-url-or-throw';import { resolveTeamsMeetingWindowOrThrow } from 'src/features/transcripts/logic-functions/utils/resolve-teams-meeting-window-or-throw';import { isFeatureEnabled } from 'src/utils/is-feature-enabled';@@ -87,53 +84,26 @@ export const teamsListOrganizerTranscriptsHandler = async (accessToken: connection.accessToken,url: calendarPageUrl,});- const joinWebUrls = [- ...new Set(page.occurrences.map((occurrence) => occurrence.joinWebUrl)),- ];- const transcripts: ListedTranscript[] = [];-- for (const joinWebUrl of joinWebUrls) {- const meeting = await getMeetingByJoinUrl({- accessToken: connection.accessToken,- joinWebUrl,- });-- if (!isDefined(meeting)) {- continue;- }-- const occurrences = page.occurrences.filter(- (occurrence) => occurrence.joinWebUrl === joinWebUrl,- );- const meetingTranscripts = await listMeetingTranscripts({- accessToken: connection.accessToken,- meetingId: meeting.id,- });-- transcripts.push(- ...meetingTranscripts- .filter((transcript) =>- occurrences.some((occurrence) =>- isTranscriptDuringOccurrence({ transcript, occurrence }),- ),- )- .map((transcript) => ({- transcriptId: transcript.id,- meetingId: meeting.id,- subject: isNonEmptyString(meeting.subject)- ? meeting.subject- : undefined,- createdDateTime: isNonEmptyString(transcript.createdDateTime)- ? transcript.createdDateTime- : undefined,- })),- );- }+ const transcripts = await listTeamsOccurrenceTranscripts({+ accessToken: connection.accessToken,+ occurrences: page.occurrences,+ });return {success: true,connectedAccount: connection.handle,- transcripts,+ transcripts: transcripts.map(+ ({ meeting, transcript }): ListedTranscript => ({+ transcriptId: transcript.id,+ meetingId: meeting.id,+ subject: isNonEmptyString(meeting.subject)+ ? meeting.subject+ : undefined,+ createdDateTime: isNonEmptyString(transcript.createdDateTime)+ ? transcript.createdDateTime+ : undefined,+ }),+ ),nextPageUrl: page.nextPageUrl,};} catch (error) {diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-occurrence-transcript.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-occurrence-transcript.type.tsnew file mode 100644index 00000000000..7b5e640435b--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-occurrence-transcript.type.ts@@ -0,0 +1,9 @@+import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';+import { type GraphOnlineMeeting } from 'src/features/transcripts/logic-functions/types/graph-online-meeting.type';+import { type TeamsCalendarReference } from 'src/features/transcripts/logic-functions/types/teams-calendar-reference.type';++export type TeamsOccurrenceTranscript = {+ meeting: GraphOnlineMeeting;+ transcript: GraphCallTranscript;+ calendarReference?: TeamsCalendarReference;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type.tsnew file mode 100644index 00000000000..08f6f37a54e--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type.ts@@ -0,0 +1,7 @@+export type TeamsTranscriptHistoryJobPayload = {+ connectedAccountId: string;+ runId: string;+ pageIndex: number;+ attempt: number;+ nextPageUrl?: string;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-page-result.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-page-result.type.tsnew file mode 100644index 00000000000..ade2dfa9fac--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-page-result.type.ts@@ -0,0 +1,5 @@+export type TeamsTranscriptHistoryPageResult =+ | { success: true }+ | { success: true; skipped: true; reason: string }+ | { success: true; retryScheduled: true }+ | { success: false; error: string };diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-state.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-state.type.tsnew file mode 100644index 00000000000..8ee6d6ec381--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-state.type.ts@@ -0,0 +1,11 @@+import { type TeamsTranscriptHistoryJobPayload } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type';++export type TeamsTranscriptHistoryState = {+ runId: string;+ windowStart: string;+ windowEnd: string;+ phase: 'importing' | 'imported' | 'failed';+ pageCount: number;+ updatedAt: string;+ nextJob?: TeamsTranscriptHistoryJobPayload;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/import-teams-transcript-history-page-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/import-teams-transcript-history-page-or-throw.test.tsnew file mode 100644index 00000000000..60549011650--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/import-teams-transcript-history-page-or-throw.test.ts@@ -0,0 +1,280 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';+import { importTeamsTranscriptHistoryPageOrThrow } from 'src/features/transcripts/logic-functions/utils/import-teams-transcript-history-page-or-throw';++const { downloadMeetingTranscriptContentMock } = vi.hoisted(() => ({+ downloadMeetingTranscriptContentMock: vi.fn(),+}));++vi.mock(+ 'src/features/transcripts/logic-functions/utils/download-meeting-transcript-content',+ () => ({+ downloadMeetingTranscriptContent: downloadMeetingTranscriptContentMock,+ }),+);++vi.mock(+ 'src/features/transcripts/logic-functions/utils/find-teams-calendar-event-ids-or-throw',+ () => ({+ findTeamsCalendarEventIdsOrThrow: vi.fn().mockResolvedValue(new Map()),+ }),+);++const TRANSCRIPT_CONTENT = [+ 'WEBVTT',+ '',+ '00:00:01.000 --> 00:00:03.000',+ '<v Alice Martin>Hello.</v>',+ '',+].join('\n');++const buildTranscript = (transcriptId: string) => ({+ meeting: { id: 'meeting-1', subject: 'Weekly sync' },+ transcript: {+ id: transcriptId,+ createdDateTime: '2026-09-01T10:00:00Z',+ endDateTime: '2026-09-01T10:30:00Z',+ },+});++type CallRecordingRow = {+ id: string;+ status: string;+ deletedAt: string | null;+};++type CallRecordingsFilter = {+ id: { in: string[] };+ deletedAt?: { is: 'NULL' | 'NOT_NULL' };+ or?: { deletedAt?: { is: 'NULL' | 'NOT_NULL' } }[];+};++// Like Twenty, soft-deleted rows only match a filter that asks for deletedAt.+const isVisibleThroughFilter = (+ { deletedAt }: CallRecordingRow,+ filter: CallRecordingsFilter,+): boolean => {+ const deletedAtConditions = (filter.or ?? [filter]).map(+ (condition) => condition.deletedAt?.is,+ );++ if (deletedAtConditions.every((condition) => condition === undefined)) {+ return deletedAt === null;+ }++ return deletedAtConditions.includes(deletedAt === null ? 'NULL' : 'NOT_NULL');+};++const buildCoreApiClient = (rows: CallRecordingRow[]) => {+ const rowsById = new Map(rows.map((row) => [row.id, row]));++ return {+ rowsById,+ query: vi.fn(+ async (request: {+ callRecordings: { __args: { filter: CallRecordingsFilter } };+ }) => {+ const { filter } = request.callRecordings.__args;++ return {+ callRecordings: {+ edges: filter.id.in+ .map((id) => rowsById.get(id))+ .filter(+ (row): row is CallRecordingRow =>+ row !== undefined && isVisibleThroughFilter(row, filter),+ )+ .map((node) => ({ node })),+ },+ };+ },+ ),+ mutation: vi.fn(+ async (request: {+ createCallRecordings: {+ __args: { data: { id: string; status: string }[] };+ };+ }) => {+ for (const { id, status } of request.createCallRecordings.__args.data) {+ rowsById.set(id, { id, status, deletedAt: null });+ }++ return {};+ },+ ),+ };+};++const getWrittenTranscriptIds = (+ coreApiClient: ReturnType<typeof buildCoreApiClient>,+ transcriptIds: string[],+): string[] => {+ const writtenCallRecordingIds = coreApiClient.mutation.mock.calls.flatMap(+ ([request]) => request.createCallRecordings.__args.data.map(({ id }) => id),+ );++ return transcriptIds.filter((transcriptId) =>+ writtenCallRecordingIds.includes(+ computeCallRecordingIdForTeamsTranscript(transcriptId),+ ),+ );+};++const buildRow = (+ transcriptId: string,+ status: string,+ deletedAt: string | null = null,+): CallRecordingRow => ({+ id: computeCallRecordingIdForTeamsTranscript(transcriptId),+ status,+ deletedAt,+});++describe('importTeamsTranscriptHistoryPageOrThrow', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ downloadMeetingTranscriptContentMock.mockResolvedValue(TRANSCRIPT_CONTENT);+ });++ it('should write new and unfinished transcripts and leave completed and deleted recordings alone', async () => {+ const transcriptIds = ['completed', 'deleted', 'processing', 'new'];+ const coreApiClient = buildCoreApiClient([+ buildRow('completed', 'COMPLETED'),+ buildRow('deleted', 'COMPLETED', '2026-09-02T00:00:00.000Z'),+ buildRow('processing', 'PROCESSING'),+ ]);++ await expect(+ importTeamsTranscriptHistoryPageOrThrow({+ accessToken: 'token',+ coreApiClient,+ transcripts: transcriptIds.map(buildTranscript),+ isRunActive: async () => true,+ }),+ ).resolves.toBe(2);+ expect(getWrittenTranscriptIds(coreApiClient, transcriptIds)).toEqual([+ 'processing',+ 'new',+ ]);+ expect(downloadMeetingTranscriptContentMock).toHaveBeenCalledTimes(2);+ });++ it('should not bring back a recording deleted while the page downloaded it', async () => {+ const transcriptIds = ['deleted-during-import', 'new'];+ const coreApiClient = buildCoreApiClient([+ buildRow('deleted-during-import', 'PROCESSING'),+ ]);++ downloadMeetingTranscriptContentMock.mockImplementation(async () => {+ coreApiClient.rowsById.set(+ computeCallRecordingIdForTeamsTranscript('deleted-during-import'),+ buildRow(+ 'deleted-during-import',+ 'PROCESSING',+ '2026-09-15T00:01:00.000Z',+ ),+ );++ return TRANSCRIPT_CONTENT;+ });++ await expect(+ importTeamsTranscriptHistoryPageOrThrow({+ accessToken: 'token',+ coreApiClient,+ transcripts: transcriptIds.map(buildTranscript),+ isRunActive: async () => true,+ }),+ ).resolves.toBe(1);+ expect(getWrittenTranscriptIds(coreApiClient, transcriptIds)).toEqual([+ 'new',+ ]);+ });++ it('should skip transcripts with no content or gone from Microsoft', async () => {+ const transcriptIds = ['empty', 'gone', 'new'];+ const coreApiClient = buildCoreApiClient([]);++ downloadMeetingTranscriptContentMock+ .mockResolvedValueOnce('WEBVTT\n')+ .mockRejectedValueOnce(+ new GraphRequestError({+ message: 'Microsoft Graph request failed (404)',+ status: 404,+ innerErrorCode: undefined,+ }),+ );++ await expect(+ importTeamsTranscriptHistoryPageOrThrow({+ accessToken: 'token',+ coreApiClient,+ transcripts: transcriptIds.map(buildTranscript),+ isRunActive: async () => true,+ }),+ ).resolves.toBe(1);+ expect(getWrittenTranscriptIds(coreApiClient, transcriptIds)).toEqual([+ 'new',+ ]);+ });++ it('should fail the page when Microsoft Graph fails for another reason', async () => {+ downloadMeetingTranscriptContentMock.mockRejectedValue(+ new GraphRequestError({+ message: 'Microsoft Graph request failed (503)',+ status: 503,+ innerErrorCode: undefined,+ }),+ );++ await expect(+ importTeamsTranscriptHistoryPageOrThrow({+ accessToken: 'token',+ coreApiClient: buildCoreApiClient([]),+ transcripts: [buildTranscript('new')],+ isRunActive: async () => true,+ }),+ ).rejects.toThrow('503');+ });++ it('should write every transcript of a long page once, in batches', async () => {+ const transcriptIds = [+ ...Array.from({ length: 11 }, (_, index) => `new-${index}`),+ 'new-0',+ ];+ const coreApiClient = buildCoreApiClient([]);++ await expect(+ importTeamsTranscriptHistoryPageOrThrow({+ accessToken: 'token',+ coreApiClient,+ transcripts: transcriptIds.map(buildTranscript),+ isRunActive: async () => true,+ }),+ ).resolves.toBe(11);+ expect(coreApiClient.mutation).toHaveBeenCalledTimes(2);+ expect(coreApiClient.rowsById.size).toBe(11);+ });++ it('should stop writing once the run is removed', async () => {+ const coreApiClient = buildCoreApiClient([]);+ const isRunActive = vi+ .fn()+ .mockResolvedValueOnce(true)+ .mockResolvedValue(false);++ await expect(+ importTeamsTranscriptHistoryPageOrThrow({+ accessToken: 'token',+ coreApiClient,+ transcripts: Array.from({ length: 11 }, (_, index) =>+ buildTranscript(`new-${index}`),+ ),+ isRunActive,+ }),+ ).resolves.toBe(10);+ expect(coreApiClient.mutation).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/is-unavailable-teams-transcript-error.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/is-unavailable-teams-transcript-error.test.tsnew file mode 100644index 00000000000..051a483133d--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/is-unavailable-teams-transcript-error.test.ts@@ -0,0 +1,37 @@+import { AppConnectionAuthFailedError } from 'twenty-sdk/logic-function';+import { describe, expect, it } from 'vitest';++import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { isUnavailableTeamsTranscriptError } from 'src/features/transcripts/logic-functions/utils/is-unavailable-teams-transcript-error';++const buildGraphRequestError = (status: number, innerErrorCode?: string) =>+ new GraphRequestError({+ message: `Microsoft Graph request failed (${status})`,+ status,+ innerErrorCode,+ });++describe('isUnavailableTeamsTranscriptError', () => {+ it.each([+ [+ 'a transcript Microsoft Graph cannot find',+ buildGraphRequestError(404),+ true,+ ],+ ['a transcript the account cannot read', buildGraphRequestError(403), true],+ [+ 'transcripts disabled by an admin',+ buildGraphRequestError(403, 'GraphAccessToTranscriptsDisabled'),+ false,+ ],+ ['a rejected token', buildGraphRequestError(401), false],+ ['a Microsoft Graph outage', buildGraphRequestError(503), false],+ [+ 'a broken connection',+ new AppConnectionAuthFailedError('connected-account-1'),+ false,+ ],+ ])('should tell whether %s is unavailable', (_, error, isUnavailable) => {+ expect(isUnavailableTeamsTranscriptError(error)).toBe(isUnavailable);+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/list-teams-occurrence-transcripts.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/list-teams-occurrence-transcripts.test.tsnew file mode 100644index 00000000000..cb22f410d22--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/list-teams-occurrence-transcripts.test.ts@@ -0,0 +1,127 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { listTeamsOccurrenceTranscripts } from 'src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts';++const { getMeetingByJoinUrlMock, listMeetingTranscriptsMock } = vi.hoisted(+ () => ({+ getMeetingByJoinUrlMock: vi.fn(),+ listMeetingTranscriptsMock: vi.fn(),+ }),+);++vi.mock(+ 'src/features/transcripts/logic-functions/utils/get-meeting-by-join-url',+ () => ({ getMeetingByJoinUrl: getMeetingByJoinUrlMock }),+);++vi.mock(+ 'src/features/transcripts/logic-functions/utils/list-meeting-transcripts',+ () => ({ listMeetingTranscripts: listMeetingTranscriptsMock }),+);++const buildOccurrence = (joinWebUrl: string, startDateTime: string) => ({+ joinWebUrl,+ startDateTime,+ endDateTime: new Date(Date.parse(startDateTime) + 30 * 60_000).toISOString(),+ calendarReference: { eventExternalId: `event-${startDateTime}` },+});++const WEEKLY_SYNC_OCCURRENCES = [+ buildOccurrence('weekly-sync', '2026-09-01T10:00:00.000Z'),+ buildOccurrence('weekly-sync', '2026-09-08T10:00:00.000Z'),+];++describe('listTeamsOccurrenceTranscripts', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ getMeetingByJoinUrlMock.mockImplementation(async ({ joinWebUrl }) => ({+ id: `meeting-${joinWebUrl}`,+ }));+ });++ it('should list the transcripts recorded during the listed occurrences of each meeting', async () => {+ listMeetingTranscriptsMock.mockResolvedValue([+ { id: 'first-week', createdDateTime: '2026-09-01T10:05:00Z' },+ { id: 'second-week', createdDateTime: '2026-09-08T10:05:00Z' },+ { id: 'other-week', createdDateTime: '2026-09-15T10:05:00Z' },+ ]);++ const transcripts = await listTeamsOccurrenceTranscripts({+ accessToken: 'token',+ occurrences: WEEKLY_SYNC_OCCURRENCES,+ });++ expect(+ transcripts.map(({ transcript, calendarReference }) => [+ transcript.id,+ calendarReference?.eventExternalId,+ ]),+ ).toEqual([+ ['first-week', 'event-2026-09-01T10:00:00.000Z'],+ ['second-week', 'event-2026-09-08T10:00:00.000Z'],+ ]);+ expect(getMeetingByJoinUrlMock).toHaveBeenCalledTimes(1);+ });++ it('should skip a meeting whose transcripts Microsoft Graph cannot list', async () => {+ listMeetingTranscriptsMock.mockImplementation(async ({ meetingId }) => {+ if (meetingId === 'meeting-weekly-sync') {+ throw new GraphRequestError({+ message: 'Microsoft Graph request failed (403)',+ status: 403,+ innerErrorCode: undefined,+ });+ }++ return [{ id: 'standup', createdDateTime: '2026-09-02T09:05:00Z' }];+ });++ const transcripts = await listTeamsOccurrenceTranscripts({+ accessToken: 'token',+ occurrences: [+ ...WEEKLY_SYNC_OCCURRENCES,+ buildOccurrence('standup', '2026-09-02T09:00:00.000Z'),+ ],+ });++ expect(transcripts.map(({ transcript }) => transcript.id)).toEqual([+ 'standup',+ ]);+ });++ it('should fail when Microsoft Graph fails for another reason', async () => {+ listMeetingTranscriptsMock.mockRejectedValue(+ new GraphRequestError({+ message: 'Microsoft Graph request failed (503)',+ status: 503,+ innerErrorCode: undefined,+ }),+ );++ await expect(+ listTeamsOccurrenceTranscripts({+ accessToken: 'token',+ occurrences: WEEKLY_SYNC_OCCURRENCES,+ }),+ ).rejects.toThrow('503');+ });++ it('should fail when Microsoft Graph refuses the meeting lookup', async () => {+ getMeetingByJoinUrlMock.mockRejectedValue(+ new GraphRequestError({+ message: 'Microsoft Graph request failed (403)',+ status: 403,+ innerErrorCode: undefined,+ }),+ );++ await expect(+ listTeamsOccurrenceTranscripts({+ accessToken: 'token',+ occurrences: WEEKLY_SYNC_OCCURRENCES,+ }),+ ).rejects.toThrow('403');+ expect(listMeetingTranscriptsMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/process-teams-transcript-history-page-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/process-teams-transcript-history-page-or-throw.test.tsnew file mode 100644index 00000000000..258a48b42b4--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/process-teams-transcript-history-page-or-throw.test.ts@@ -0,0 +1,273 @@+import { AppConnectionAuthFailedError } from 'twenty-sdk/logic-function';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { processTeamsTranscriptHistoryPageOrThrow } from 'src/features/transcripts/logic-functions/utils/process-teams-transcript-history-page-or-throw';++const {+ kvStore,+ enqueueJobsMock,+ listTeamsCalendarPageMock,+ importTeamsTranscriptHistoryPageMock,+ listConnectionsMock,+} = vi.hoisted(() => ({+ kvStore: new Map<string, unknown>(),+ enqueueJobsMock: vi.fn(),+ listTeamsCalendarPageMock: vi.fn(),+ importTeamsTranscriptHistoryPageMock: vi.fn(),+ listConnectionsMock: vi.fn(),+}));++vi.mock('src/constants/feature-flags', () => ({+ FEATURE_FLAGS: { IS_TRANSCRIPT_IMPORT_ENABLED: true },+}));++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ kv: {+ get: async (key: string) => kvStore.get(key) ?? null,+ set: async (key: string, value: unknown) => {+ kvStore.set(key, value);+ },+ delete: async (key: string) => {+ kvStore.delete(key);+ },+ },+ listConnections: listConnectionsMock,+ getConnection: vi.fn().mockResolvedValue({ accessToken: 'token' }),+ enqueueJobs: enqueueJobsMock,+}));++vi.mock('twenty-client-sdk/core', () => ({+ CoreApiClient: vi.fn(),+}));++vi.mock(+ 'src/features/transcripts/logic-functions/utils/list-teams-calendar-page',+ () => ({ listTeamsCalendarPage: listTeamsCalendarPageMock }),+);++vi.mock(+ 'src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts',+ () => ({ listTeamsOccurrenceTranscripts: vi.fn().mockResolvedValue([]) }),+);++vi.mock(+ 'src/features/transcripts/logic-functions/utils/import-teams-transcript-history-page-or-throw',+ () => ({+ importTeamsTranscriptHistoryPageOrThrow:+ importTeamsTranscriptHistoryPageMock,+ }),+);++const STATE_KV_KEY = 'teams-transcript-history:connected-account-1';++const NEXT_PAGE_URL =+ 'https://graph.microsoft.com/v1.0/me/calendarView?$skiptoken=abc';++const JOB = {+ connectedAccountId: 'connected-account-1',+ runId: 'run-1',+ pageIndex: 2,+ attempt: 0,+};++const NEXT_JOB = { ...JOB, pageIndex: 3, nextPageUrl: NEXT_PAGE_URL };++const STATE = {+ runId: 'run-1',+ windowStart: '2026-08-15T00:00:00.000Z',+ windowEnd: '2026-09-15T00:00:00.000Z',+ phase: 'importing',+ pageCount: 2,+ updatedAt: '2026-09-15T00:10:00.000Z',+};++const buildGraphRequestError = (status: number, innerErrorCode?: string) =>+ new GraphRequestError({+ message: `Microsoft Graph request failed (${status})`,+ status,+ innerErrorCode,+ });++const getEnqueuedJobs = () =>+ enqueueJobsMock.mock.calls.map(([request]) => ({+ payload: request.jobs[0].payload,+ delayMs: request.delayMs,+ }));++describe('processTeamsTranscriptHistoryPageOrThrow', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ kvStore.clear();+ process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY] = 'true';+ enqueueJobsMock.mockResolvedValue(undefined);+ listConnectionsMock.mockResolvedValue([{ id: 'connected-account-1' }]);+ listTeamsCalendarPageMock.mockResolvedValue({+ occurrences: [],+ nextPageUrl: NEXT_PAGE_URL,+ });+ importTeamsTranscriptHistoryPageMock.mockResolvedValue(2);+ });++ it('should save the page before scheduling the next one a minute later', async () => {+ let stateWhenScheduled: unknown;++ kvStore.set(STATE_KV_KEY, STATE);+ enqueueJobsMock.mockImplementation(async () => {+ stateWhenScheduled = kvStore.get(STATE_KV_KEY);+ });++ await processTeamsTranscriptHistoryPageOrThrow(JOB);++ expect(stateWhenScheduled).toMatchObject({+ phase: 'importing',+ pageCount: 3,+ nextJob: NEXT_JOB,+ });+ expect(getEnqueuedJobs()).toEqual([{ payload: NEXT_JOB, delayMs: 60_000 }]);+ });++ it('should schedule the next page right away when the page imported nothing', async () => {+ kvStore.set(STATE_KV_KEY, STATE);+ importTeamsTranscriptHistoryPageMock.mockResolvedValue(0);++ await processTeamsTranscriptHistoryPageOrThrow(JOB);++ expect(getEnqueuedJobs()).toEqual([{ payload: NEXT_JOB, delayMs: 0 }]);+ });++ it('should finish the run on the last calendar page', async () => {+ kvStore.set(STATE_KV_KEY, STATE);+ listTeamsCalendarPageMock.mockResolvedValue({ occurrences: [] });++ await processTeamsTranscriptHistoryPageOrThrow(JOB);++ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({+ phase: 'imported',+ pageCount: 3,+ });+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });++ it('should stop a page whose run is removed while it imports', async () => {+ let wasRunActive: boolean | undefined;++ kvStore.set(STATE_KV_KEY, STATE);+ importTeamsTranscriptHistoryPageMock.mockImplementation(+ async ({ isRunActive }: { isRunActive: () => Promise<boolean> }) => {+ kvStore.delete(STATE_KV_KEY);+ wasRunActive = await isRunActive();++ return 0;+ },+ );++ await expect(+ processTeamsTranscriptHistoryPageOrThrow(JOB),+ ).resolves.toEqual(expect.objectContaining({ skipped: true }));+ expect(wasRunActive).toBe(false);+ expect(kvStore.has(STATE_KV_KEY)).toBe(false);+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });++ it('should not leave a run behind for a connection removed while its page was saved', async () => {+ kvStore.set(STATE_KV_KEY, STATE);+ listConnectionsMock.mockResolvedValue([]);++ await expect(+ processTeamsTranscriptHistoryPageOrThrow(JOB),+ ).resolves.toEqual(expect.objectContaining({ skipped: true }));+ expect(kvStore.has(STATE_KV_KEY)).toBe(false);+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });++ it('should only schedule the saved next page when a retried page was already saved', async () => {+ kvStore.set(STATE_KV_KEY, { ...STATE, pageCount: 3, nextJob: NEXT_JOB });++ await expect(+ processTeamsTranscriptHistoryPageOrThrow(JOB),+ ).resolves.toEqual(expect.objectContaining({ skipped: true }));+ expect(listTeamsCalendarPageMock).not.toHaveBeenCalled();+ expect(getEnqueuedJobs()).toEqual([{ payload: NEXT_JOB, delayMs: 0 }]);+ });++ it.each([+ ['was replaced by another run', { ...STATE, runId: 'run-2' }],+ ['moved past this page', { ...STATE, pageCount: 5 }],+ ['failed', { ...STATE, phase: 'failed' }],+ ])('should leave a run alone when it %s', async (_, state) => {+ kvStore.set(STATE_KV_KEY, state);++ await expect(+ processTeamsTranscriptHistoryPageOrThrow(JOB),+ ).resolves.toEqual(expect.objectContaining({ skipped: true }));+ expect(kvStore.get(STATE_KV_KEY)).toBe(state);+ expect(listTeamsCalendarPageMock).not.toHaveBeenCalled();+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });++ it('should retry a failed page later and keep the run from looking stalled', async () => {+ kvStore.set(STATE_KV_KEY, STATE);+ listTeamsCalendarPageMock.mockRejectedValue(buildGraphRequestError(503));++ await processTeamsTranscriptHistoryPageOrThrow(JOB);++ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({+ phase: 'importing',+ pageCount: 2,+ });+ expect((kvStore.get(STATE_KV_KEY) as typeof STATE).updatedAt).not.toBe(+ STATE.updatedAt,+ );+ expect(getEnqueuedJobs()).toEqual([+ { payload: { ...JOB, attempt: 1 }, delayMs: 60_000 },+ ]);+ });++ it.each([+ ['its last retry failed', 3, buildGraphRequestError(503)],+ [+ 'an admin disabled transcripts',+ 0,+ buildGraphRequestError(403, 'GraphAccessToTranscriptsDisabled'),+ ],+ [+ 'its connection needs reconnecting',+ 0,+ new AppConnectionAuthFailedError('connected-account-1'),+ ],+ ])('should fail the run when %s', async (_, attempt, error) => {+ kvStore.set(STATE_KV_KEY, STATE);+ listTeamsCalendarPageMock.mockRejectedValue(error);++ await expect(+ processTeamsTranscriptHistoryPageOrThrow({ ...JOB, attempt }),+ ).resolves.toEqual(expect.objectContaining({ success: false }));+ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({ phase: 'failed' });+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });++ it('should retry a rejected token, since a page can outlive its token', async () => {+ kvStore.set(STATE_KV_KEY, STATE);+ listTeamsCalendarPageMock.mockRejectedValue(buildGraphRequestError(401));++ await processTeamsTranscriptHistoryPageOrThrow({ ...JOB, attempt: 1 });++ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({ phase: 'importing' });+ expect(getEnqueuedJobs()).toEqual([+ { payload: { ...JOB, attempt: 2 }, delayMs: 5 * 60_000 },+ ]);+ });++ it('should reject a malformed job without touching the run', async () => {+ kvStore.set(STATE_KV_KEY, STATE);++ await expect(+ processTeamsTranscriptHistoryPageOrThrow({ ...JOB, pageIndex: -1 }),+ ).resolves.toEqual(expect.objectContaining({ success: false }));+ expect(kvStore.get(STATE_KV_KEY)).toBe(STATE);+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/start-teams-transcript-history-initial-import-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/start-teams-transcript-history-initial-import-or-throw.test.tsnew file mode 100644index 00000000000..9ae6a8fd4a6--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/start-teams-transcript-history-initial-import-or-throw.test.ts@@ -0,0 +1,149 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';+import { startTeamsTranscriptHistoryInitialImportOrThrow } from 'src/features/transcripts/logic-functions/utils/start-teams-transcript-history-initial-import-or-throw';++const { kvStore, enqueueJobsMock, listConnectionsMock } = vi.hoisted(() => ({+ kvStore: new Map<string, unknown>(),+ enqueueJobsMock: vi.fn(),+ listConnectionsMock: vi.fn(),+}));++vi.mock('src/constants/feature-flags', () => ({+ FEATURE_FLAGS: { IS_TRANSCRIPT_IMPORT_ENABLED: true },+}));++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ kv: {+ get: async (key: string) => kvStore.get(key) ?? null,+ set: async (key: string, value: unknown) => {+ kvStore.set(key, value);+ },+ delete: async (key: string) => {+ kvStore.delete(key);+ },+ },+ enqueueJobs: enqueueJobsMock,+ listConnections: listConnectionsMock,+}));++const CONNECTED_ACCOUNT_ID = 'connected-account-1';++const STATE_KV_KEY = `teams-transcript-history:${CONNECTED_ACCOUNT_ID}`;++const NOW = Date.parse('2026-09-15T00:00:00.000Z');++const EXISTING_STATE = {+ runId: 'run-1',+ windowStart: '2026-08-15T00:00:00.000Z',+ windowEnd: '2026-09-15T00:00:00.000Z',+ phase: 'importing',+ pageCount: 2,+ updatedAt: new Date(NOW - 60_000).toISOString(),+};++const startInitialImport = () =>+ startTeamsTranscriptHistoryInitialImportOrThrow({+ connectedAccountId: CONNECTED_ACCOUNT_ID,+ });++describe('startTeamsTranscriptHistoryInitialImportOrThrow', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.useFakeTimers({ now: NOW });+ kvStore.clear();+ process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY] = 'true';+ enqueueJobsMock.mockResolvedValue(undefined);+ listConnectionsMock.mockResolvedValue([{ id: CONNECTED_ACCOUNT_ID }]);+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('should import the last 31 days of a new connection', async () => {+ await startInitialImport();++ const state = kvStore.get(STATE_KV_KEY) as typeof EXISTING_STATE;++ expect(state).toMatchObject({+ windowStart: '2026-08-15T00:00:00.000Z',+ windowEnd: '2026-09-15T00:00:00.000Z',+ phase: 'importing',+ pageCount: 0,+ });+ expect(enqueueJobsMock).toHaveBeenCalledWith(+ expect.objectContaining({+ jobs: [+ expect.objectContaining({+ payload: {+ connectedAccountId: CONNECTED_ACCOUNT_ID,+ runId: state.runId,+ pageIndex: 0,+ attempt: 0,+ },+ }),+ ],+ }),+ );+ });++ it.each([+ ['is running', EXISTING_STATE],+ ['finished', { ...EXISTING_STATE, phase: 'imported' }],+ ])('should keep an import that %s', async (_, existingState) => {+ kvStore.set(STATE_KV_KEY, existingState);++ await startInitialImport();++ expect(kvStore.get(STATE_KV_KEY)).toBe(existingState);+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });++ it.each([+ ['failed', { ...EXISTING_STATE, phase: 'failed' }],+ [+ 'stalled',+ {+ ...EXISTING_STATE,+ updatedAt: new Date(NOW - 41 * 60_000).toISOString(),+ },+ ],+ ])('should restart an import that %s', async (_, existingState) => {+ kvStore.set(STATE_KV_KEY, existingState);++ await startInitialImport();++ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({+ phase: 'importing',+ pageCount: 0,+ });+ expect(kvStore.get(STATE_KV_KEY)).not.toMatchObject({ runId: 'run-1' });+ expect(enqueueJobsMock).toHaveBeenCalledTimes(1);+ });++ it('should mark the import failed when its first page cannot be scheduled', async () => {+ enqueueJobsMock.mockRejectedValue(new Error('queue unavailable'));++ await expect(startInitialImport()).rejects.toThrow('queue unavailable');+ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({ phase: 'failed' });+ });++ it('should remove the import state of a connection removed while it started', async () => {+ listConnectionsMock.mockResolvedValue([]);++ await startInitialImport();++ expect(kvStore.has(STATE_KV_KEY)).toBe(false);+ });++ it('should not import anything while transcripts are off', async () => {+ process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY] = 'false';++ await startInitialImport();++ expect(kvStore.size).toBe(0);+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-history-kv-key.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-history-kv-key.tsnew file mode 100644index 00000000000..cbddb139e29--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-history-kv-key.ts@@ -0,0 +1,5 @@+import { TEAMS_TRANSCRIPT_HISTORY_KV_KEY_PREFIX } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-kv-key-prefix';++export const buildTeamsTranscriptHistoryKvKey = (+ connectedAccountId: string,+): string => `${TEAMS_TRANSCRIPT_HISTORY_KV_KEY_PREFIX}:${connectedAccountId}`;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/delete-teams-transcript-history-kv-keys.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/delete-teams-transcript-history-kv-keys.tsnew file mode 100644index 00000000000..d7e60124493--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/delete-teams-transcript-history-kv-keys.ts@@ -0,0 +1,11 @@+import { kv } from 'twenty-sdk/logic-function';++import { buildTeamsTranscriptHistoryKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-history-kv-key';++export const deleteTeamsTranscriptHistoryKvKeys = async ({+ connectedAccountId,+}: {+ connectedAccountId: string;+}): Promise<void> => {+ await kv.delete(buildTeamsTranscriptHistoryKvKey(connectedAccountId));+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-history-job-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-history-job-or-throw.tsnew file mode 100644index 00000000000..f67ee6b10a8--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-history-job-or-throw.ts@@ -0,0 +1,36 @@+import {+ enqueueJobs,+ RetryableLogicFunctionError,+} from 'twenty-sdk/logic-function';++import { TEAMS_IMPORT_TRANSCRIPT_HISTORY_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 { type TeamsTranscriptHistoryJobPayload } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type';+import { toErrorMessage } from 'src/utils/to-error-message';++export const enqueueTeamsTranscriptHistoryJobOrThrow = async ({+ job,+ delayMilliseconds,+}: {+ job: TeamsTranscriptHistoryJobPayload;+ delayMilliseconds: number;+}): Promise<void> => {+ try {+ await enqueueJobs({+ logicFunctionUniversalIdentifier:+ TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER,+ jobs: [+ {+ jobId: `teams-transcript-history-importing-${job.runId}-${job.pageIndex}-${job.attempt}`,+ payload: job,+ },+ ],+ retryLimit: TEAMS_TRANSCRIPT_IMPORT_JOB_RETRY_LIMIT,+ delayMs: delayMilliseconds,+ });+ } catch (error) {+ throw new RetryableLogicFunctionError(+ `Could not schedule Teams transcript history page ${job.pageIndex}: ${toErrorMessage(error)}`,+ );+ }+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-deleted-and-completed-call-recording-ids-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-deleted-and-completed-call-recording-ids-or-throw.tsnew file mode 100644index 00000000000..67387ad07b2--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-deleted-and-completed-call-recording-ids-or-throw.ts@@ -0,0 +1,63 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'twenty-sdk/utils';++type ExistingCallRecording = {+ id: string;+ status: string | null;+ deletedAt: string | null;+};++export const findDeletedAndCompletedCallRecordingIdsOrThrow = async ({+ coreApiClient,+ callRecordingIds,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ callRecordingIds: string[];+}): Promise<{+ deletedCallRecordingIds: Set<string>;+ completedCallRecordingIds: Set<string>;+}> => {+ if (callRecordingIds.length === 0) {+ return {+ deletedCallRecordingIds: new Set(),+ completedCallRecordingIds: new Set(),+ };+ }++ const result: {+ callRecordings?: { edges?: { node: ExistingCallRecording }[] };+ } = await coreApiClient.query({+ callRecordings: {+ __args: {+ filter: {+ id: { in: callRecordingIds },+ or: [+ { deletedAt: { is: 'NULL' } },+ { deletedAt: { is: 'NOT_NULL' } },+ ],+ },+ first: callRecordingIds.length,+ },+ edges: { node: { id: true, status: true, deletedAt: true } },+ },+ });+ const callRecordings =+ result.callRecordings?.edges?.map((edge) => edge.node) ?? [];++ return {+ deletedCallRecordingIds: new Set(+ callRecordings+ .filter((callRecording) => isDefined(callRecording.deletedAt))+ .map((callRecording) => callRecording.id),+ ),+ completedCallRecordingIds: new Set(+ callRecordings+ .filter(+ (callRecording) =>+ !isDefined(callRecording.deletedAt) &&+ callRecording.status === 'COMPLETED',+ )+ .map((callRecording) => callRecording.id),+ ),+ };+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-history-page-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-history-page-or-throw.tsnew file mode 100644index 00000000000..170d7f943e7--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/import-teams-transcript-history-page-or-throw.ts@@ -0,0 +1,158 @@+import { isNonEmptyArray } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'twenty-sdk/utils';++import { TEAMS_TRANSCRIPT_HISTORY_UPSERT_BATCH_SIZE } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-upsert-batch-size';+import { type TeamsOccurrenceTranscript } from 'src/features/transcripts/logic-functions/types/teams-occurrence-transcript.type';+import { buildTeamsCallRecordingSyncFields } from 'src/features/transcripts/logic-functions/utils/build-teams-call-recording-sync-fields';+import { chunkIntoBatches } from 'src/features/transcripts/logic-functions/utils/chunk-into-batches';+import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';+import { downloadMeetingTranscriptContent } from 'src/features/transcripts/logic-functions/utils/download-meeting-transcript-content';+import { findDeletedAndCompletedCallRecordingIdsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-deleted-and-completed-call-recording-ids-or-throw';+import { findTeamsCalendarEventIdsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-teams-calendar-event-ids-or-throw';+import { isUnavailableTeamsTranscriptError } from 'src/features/transcripts/logic-functions/utils/is-unavailable-teams-transcript-error';+import { mapTeamsTranscriptToEntries } from 'src/features/transcripts/logic-functions/utils/map-teams-transcript-to-entries';+import { toCallRecordingData } from 'src/features/transcripts/logic-functions/utils/to-call-recording-data';++const downloadAvailableTranscriptContentOrThrow = async ({+ accessToken,+ meetingId,+ transcriptId,+}: {+ accessToken: string;+ meetingId: string;+ transcriptId: string;+}): Promise<string | undefined> => {+ try {+ return await downloadMeetingTranscriptContent({+ accessToken,+ meetingId,+ transcriptId,+ });+ } catch (error) {+ if (isUnavailableTeamsTranscriptError(error)) {+ return undefined;+ }++ throw error;+ }+};++export const importTeamsTranscriptHistoryPageOrThrow = async ({+ accessToken,+ coreApiClient,+ transcripts,+ isRunActive,+}: {+ accessToken: string;+ coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;+ transcripts: TeamsOccurrenceTranscript[];+ isRunActive: () => Promise<boolean>;+}): Promise<number> => {+ const pageTranscripts = [+ ...new Map(+ transcripts.map((occurrenceTranscript) => {+ const callRecordingId = computeCallRecordingIdForTeamsTranscript(+ occurrenceTranscript.transcript.id,+ );++ return [callRecordingId, { ...occurrenceTranscript, callRecordingId }];+ }),+ ).values(),+ ];+ const { deletedCallRecordingIds, completedCallRecordingIds } =+ await findDeletedAndCompletedCallRecordingIdsOrThrow({+ coreApiClient,+ callRecordingIds: pageTranscripts.map(+ ({ callRecordingId }) => callRecordingId,+ ),+ });+ const importableTranscripts = pageTranscripts.filter(+ ({ callRecordingId }) =>+ !deletedCallRecordingIds.has(callRecordingId) &&+ !completedCallRecordingIds.has(callRecordingId),+ );+ const calendarEventIds = await findTeamsCalendarEventIdsOrThrow({+ accessToken,+ coreApiClient,+ references: importableTranscripts+ .map(({ calendarReference }) => calendarReference)+ .filter(isDefined),+ });+ let importedCount = 0;++ for (const transcriptBatch of chunkIntoBatches(+ importableTranscripts,+ TEAMS_TRANSCRIPT_HISTORY_UPSERT_BATCH_SIZE,+ )) {+ const callRecordings: (ReturnType<typeof toCallRecordingData> & {+ id: string;+ })[] = [];++ for (const {+ meeting,+ transcript,+ calendarReference,+ callRecordingId,+ } of transcriptBatch) {+ const transcriptContent = await downloadAvailableTranscriptContentOrThrow(+ {+ accessToken,+ meetingId: meeting.id,+ transcriptId: transcript.id,+ },+ );+ const transcriptEntries = isDefined(transcriptContent)+ ? mapTeamsTranscriptToEntries(transcriptContent)+ : [];++ if (!isNonEmptyArray(transcriptEntries)) {+ continue;+ }++ callRecordings.push({+ id: callRecordingId,+ ...toCallRecordingData(+ buildTeamsCallRecordingSyncFields({+ meeting,+ transcript,+ transcriptEntries,+ calendarEventId: isDefined(calendarReference)+ ? calendarEventIds.get(calendarReference.eventExternalId)+ : undefined,+ }),+ ),+ });+ }++ // The batch upsert would bring back a recording deleted while it downloaded.+ const callRecordingIdsBeforeWrite =+ await findDeletedAndCompletedCallRecordingIdsOrThrow({+ coreApiClient,+ callRecordingIds: callRecordings.map(({ id }) => id),+ });+ const upsertableCallRecordings = callRecordings.filter(+ ({ id }) =>+ !callRecordingIdsBeforeWrite.deletedCallRecordingIds.has(id) &&+ !callRecordingIdsBeforeWrite.completedCallRecordingIds.has(id),+ );++ if (upsertableCallRecordings.length === 0) {+ continue;+ }++ if (!(await isRunActive())) {+ break;+ }++ await coreApiClient.mutation({+ createCallRecordings: {+ __args: { data: upsertableCallRecordings, upsert: true },+ id: true,+ },+ });+ importedCount += upsertableCallRecordings.length;+ }++ return importedCount;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-connection-listed.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-connection-listed.tsnew file mode 100644index 00000000000..528f72ff74a--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-connection-listed.ts@@ -0,0 +1,10 @@+import { listConnections } from 'twenty-sdk/logic-function';++import { TEAMS_PROVIDER_NAME } from 'src/features/transcripts/constants/teams-provider-name';++export const isTeamsConnectionListed = async (+ connectedAccountId: string,+): Promise<boolean> =>+ (await listConnections({ providerName: TEAMS_PROVIDER_NAME })).some(+ (connection) => connection.id === connectedAccountId,+ );diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-transcript-history-stalled.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-transcript-history-stalled.tsnew file mode 100644index 00000000000..515bb601054--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-transcript-history-stalled.ts@@ -0,0 +1,13 @@+import { TEAMS_TRANSCRIPT_HISTORY_STALL_THRESHOLD_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-stall-threshold-milliseconds';+import { type TeamsTranscriptHistoryState } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-state.type';++export const isTeamsTranscriptHistoryStalled = ({+ state,+ now,+}: {+ state: Pick<TeamsTranscriptHistoryState, 'phase' | 'updatedAt'>;+ now: number;+}): boolean =>+ state.phase === 'importing' &&+ now - Date.parse(state.updatedAt) >+ TEAMS_TRANSCRIPT_HISTORY_STALL_THRESHOLD_MILLISECONDS;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-unavailable-teams-transcript-error.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-unavailable-teams-transcript-error.tsnew file mode 100644index 00000000000..0de3cc350ab--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-unavailable-teams-transcript-error.ts@@ -0,0 +1,9 @@+import { GRAPH_ACCESS_TO_TRANSCRIPTS_DISABLED_ERROR_CODE } from 'src/features/transcripts/logic-functions/constants/graph-access-to-transcripts-disabled-error-code';+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';++export const isUnavailableTeamsTranscriptError = (error: unknown): boolean =>+ error instanceof GraphRequestError &&+ (error.status === 404 ||+ (error.status === 403 &&+ error.innerErrorCode !==+ GRAPH_ACCESS_TO_TRANSCRIPTS_DISABLED_ERROR_CODE));diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts.tsnew file mode 100644index 00000000000..61b23270063--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts.ts@@ -0,0 +1,96 @@+import { isDefined } from 'twenty-sdk/utils';++import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';+import { type TeamsMeetingOccurrence } from 'src/features/transcripts/logic-functions/types/teams-meeting-occurrence.type';+import { type TeamsOccurrenceTranscript } from 'src/features/transcripts/logic-functions/types/teams-occurrence-transcript.type';+import { findTeamsTranscriptCalendarReference } from 'src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-reference';+import { getMeetingByJoinUrl } from 'src/features/transcripts/logic-functions/utils/get-meeting-by-join-url';+import { isTranscriptDuringOccurrence } from 'src/features/transcripts/logic-functions/utils/is-transcript-during-occurrence';+import { isUnavailableTeamsTranscriptError } from 'src/features/transcripts/logic-functions/utils/is-unavailable-teams-transcript-error';+import { listMeetingTranscripts } from 'src/features/transcripts/logic-functions/utils/list-meeting-transcripts';+import { toErrorMessage } from 'src/utils/to-error-message';++const listAvailableMeetingTranscriptsOrThrow = async ({+ accessToken,+ meetingId,+}: {+ accessToken: string;+ meetingId: string;+}): Promise<GraphCallTranscript[]> => {+ try {+ return await listMeetingTranscripts({ accessToken, meetingId });+ } catch (error) {+ if (!isUnavailableTeamsTranscriptError(error)) {+ throw error;+ }++ console.error(+ `[teams] skipped a meeting whose transcripts Microsoft Graph could not list: ${toErrorMessage(error)}`,+ );++ return [];+ }+};++const listMeetingOccurrenceTranscriptsOrThrow = async ({+ accessToken,+ joinWebUrl,+ occurrences,+}: {+ accessToken: string;+ joinWebUrl: string;+ occurrences: TeamsMeetingOccurrence[];+}): Promise<TeamsOccurrenceTranscript[]> => {+ const meeting = await getMeetingByJoinUrl({ accessToken, joinWebUrl });++ if (!isDefined(meeting)) {+ return [];+ }++ const meetingTranscripts = await listAvailableMeetingTranscriptsOrThrow({+ accessToken,+ meetingId: meeting.id,+ });++ return meetingTranscripts+ .filter((transcript) =>+ occurrences.some((occurrence) =>+ isTranscriptDuringOccurrence({ transcript, occurrence }),+ ),+ )+ .map((transcript) => ({+ meeting,+ transcript,+ calendarReference: findTeamsTranscriptCalendarReference({+ transcript,+ occurrences,+ }),+ }));+};++export const listTeamsOccurrenceTranscripts = async ({+ accessToken,+ occurrences,+}: {+ accessToken: string;+ occurrences: TeamsMeetingOccurrence[];+}): Promise<TeamsOccurrenceTranscript[]> => {+ const joinWebUrls = [+ ...new Set(occurrences.map((occurrence) => occurrence.joinWebUrl)),+ ];+ const transcripts: TeamsOccurrenceTranscript[] = [];++ for (const joinWebUrl of joinWebUrls) {+ transcripts.push(+ ...(await listMeetingOccurrenceTranscriptsOrThrow({+ accessToken,+ joinWebUrl,+ occurrences: occurrences.filter(+ (occurrence) => occurrence.joinWebUrl === joinWebUrl,+ ),+ })),+ );+ }++ return transcripts;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/process-teams-transcript-history-page-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/process-teams-transcript-history-page-or-throw.tsnew file mode 100644index 00000000000..c7e5e5476f5--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/process-teams-transcript-history-page-or-throw.ts@@ -0,0 +1,260 @@+import { isNonEmptyString, isNonNegativeInteger } from '@sniptt/guards';+import { CoreApiClient } from 'twenty-client-sdk/core';+import {+ AppConnectionAuthFailedError,+ getConnection,+ kv,+ RetryableLogicFunctionError,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { FEATURE_FLAGS } from 'src/constants/feature-flags';+import { TEAMS_TRANSCRIPT_HISTORY_IMPORT_PAGE_DELAY_MILLISECONDS } from 'src/features/transcripts/constants/teams-transcript-history-import-page-delay-milliseconds';+import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';+import { GRAPH_ACCESS_TO_TRANSCRIPTS_DISABLED_ERROR_CODE } from 'src/features/transcripts/logic-functions/constants/graph-access-to-transcripts-disabled-error-code';+import { TEAMS_TRANSCRIPT_HISTORY_RETRY_DELAYS_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-retry-delays-milliseconds';+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { type TeamsTranscriptHistoryJobPayload } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type';+import { type TeamsTranscriptHistoryPageResult } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-page-result.type';+import { type TeamsTranscriptHistoryState } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-state.type';+import { buildTeamsCalendarViewUrl } from 'src/features/transcripts/logic-functions/utils/build-teams-calendar-view-url';+import { buildTeamsTranscriptHistoryKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-history-kv-key';+import { deleteTeamsTranscriptHistoryKvKeys } from 'src/features/transcripts/logic-functions/utils/delete-teams-transcript-history-kv-keys';+import { enqueueTeamsTranscriptHistoryJobOrThrow } from 'src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-history-job-or-throw';+import { importTeamsTranscriptHistoryPageOrThrow } from 'src/features/transcripts/logic-functions/utils/import-teams-transcript-history-page-or-throw';+import { isTeamsConnectionListed } from 'src/features/transcripts/logic-functions/utils/is-teams-connection-listed';+import { listTeamsCalendarPage } from 'src/features/transcripts/logic-functions/utils/list-teams-calendar-page';+import { listTeamsOccurrenceTranscripts } from 'src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts';+import { resolveTeamsCalendarNextPageUrlOrThrow } from 'src/features/transcripts/logic-functions/utils/resolve-teams-calendar-next-page-url-or-throw';+import { toErrorMessage } from 'src/utils/to-error-message';+import { isFeatureEnabled } from 'src/utils/is-feature-enabled';++const findStateForJob = async (+ job: TeamsTranscriptHistoryJobPayload,+): Promise<TeamsTranscriptHistoryState | undefined> => {+ const state = await kv.get<TeamsTranscriptHistoryState>(+ buildTeamsTranscriptHistoryKvKey(job.connectedAccountId),+ );++ return state?.runId === job.runId && state.phase === 'importing'+ ? state+ : undefined;+};++const isFatalError = (error: unknown): boolean =>+ error instanceof AppConnectionAuthFailedError ||+ (error instanceof GraphRequestError &&+ error.status === 403 &&+ error.innerErrorCode === GRAPH_ACCESS_TO_TRANSCRIPTS_DISABLED_ERROR_CODE);++const importPageOrThrow = async (+ job: TeamsTranscriptHistoryJobPayload,+): Promise<TeamsTranscriptHistoryPageResult> => {+ const state = await findStateForJob(job);++ if (+ !isDefined(state) ||+ (state.pageCount !== job.pageIndex && state.pageCount !== job.pageIndex + 1)+ ) {+ return {+ success: true,+ skipped: true,+ reason: 'Teams transcript history run moved on without this page',+ };+ }++ // The page was already saved, so only scheduling the next page failed.+ if (state.pageCount === job.pageIndex + 1) {+ if (isDefined(state.nextJob)) {+ await enqueueTeamsTranscriptHistoryJobOrThrow({+ job: state.nextJob,+ delayMilliseconds: 0,+ });+ }++ return {+ success: true,+ skipped: true,+ reason: 'Teams transcript history page was already imported',+ };+ }++ const { accessToken } = await getConnection(job.connectedAccountId);+ const page = await listTeamsCalendarPage({+ accessToken,+ url: isDefined(job.nextPageUrl)+ ? resolveTeamsCalendarNextPageUrlOrThrow(job.nextPageUrl)+ : buildTeamsCalendarViewUrl({+ startDateTime: state.windowStart,+ endDateTime: state.windowEnd,+ }),+ });+ const importedCount = await importTeamsTranscriptHistoryPageOrThrow({+ accessToken,+ coreApiClient: new CoreApiClient({ runAs: 'application' }),+ transcripts: await listTeamsOccurrenceTranscripts({+ accessToken,+ occurrences: page.occurrences,+ }),+ isRunActive: async () => isDefined(await findStateForJob(job)),+ });+ const currentState = await findStateForJob(job);++ if (!isDefined(currentState) || currentState.pageCount !== job.pageIndex) {+ return {+ success: true,+ skipped: true,+ reason: 'Teams transcript history run moved on during this page',+ };+ }++ const nextJob = isNonEmptyString(page.nextPageUrl)+ ? {+ ...job,+ pageIndex: job.pageIndex + 1,+ attempt: 0,+ nextPageUrl: page.nextPageUrl,+ }+ : undefined;++ await kv.set<TeamsTranscriptHistoryState>(+ buildTeamsTranscriptHistoryKvKey(job.connectedAccountId),+ {+ ...currentState,+ phase: isDefined(nextJob) ? 'importing' : 'imported',+ pageCount: job.pageIndex + 1,+ updatedAt: new Date().toISOString(),+ nextJob,+ },+ );++ // Disconnecting deletes the run state, and kv cannot make this save conditional on it.+ if (!(await isTeamsConnectionListed(job.connectedAccountId))) {+ await deleteTeamsTranscriptHistoryKvKeys({+ connectedAccountId: job.connectedAccountId,+ });++ return {+ success: true,+ skipped: true,+ reason: 'Teams connection was removed during this page',+ };+ }++ if (isDefined(nextJob)) {+ await enqueueTeamsTranscriptHistoryJobOrThrow({+ job: nextJob,+ delayMilliseconds:+ importedCount > 0+ ? TEAMS_TRANSCRIPT_HISTORY_IMPORT_PAGE_DELAY_MILLISECONDS+ : 0,+ });+ }++ return { success: true };+};++const retryOrFailPageOrThrow = async ({+ job,+ error,+}: {+ job: TeamsTranscriptHistoryJobPayload;+ error: unknown;+}): Promise<TeamsTranscriptHistoryPageResult> => {+ const state = await findStateForJob(job);++ if (!isDefined(state)) {+ return {+ success: true,+ skipped: true,+ reason: 'Teams transcript history run was replaced or removed',+ };+ }++ const stateKvKey = buildTeamsTranscriptHistoryKvKey(job.connectedAccountId);+ const retryDelayMilliseconds =+ TEAMS_TRANSCRIPT_HISTORY_RETRY_DELAYS_MILLISECONDS[job.attempt];++ if (isFatalError(error) || !isDefined(retryDelayMilliseconds)) {+ await kv.set<TeamsTranscriptHistoryState>(stateKvKey, {+ ...state,+ phase: 'failed',+ updatedAt: new Date().toISOString(),+ });++ return { success: false, error: toErrorMessage(error) };+ }++ await kv.set<TeamsTranscriptHistoryState>(stateKvKey, {+ ...state,+ updatedAt: new Date().toISOString(),+ });+ await enqueueTeamsTranscriptHistoryJobOrThrow({+ job: { ...job, attempt: job.attempt + 1 },+ delayMilliseconds: retryDelayMilliseconds,+ });++ return { success: true, retryScheduled: true };+};++export const processTeamsTranscriptHistoryPageOrThrow = async (+ payload: Partial<Record<keyof TeamsTranscriptHistoryJobPayload, unknown>>,+): Promise<TeamsTranscriptHistoryPageResult> => {+ const { connectedAccountId, runId, pageIndex, attempt, nextPageUrl } =+ payload;++ if (+ !isNonEmptyString(connectedAccountId) ||+ !isNonEmptyString(runId) ||+ !isNonNegativeInteger(pageIndex) ||+ !isNonNegativeInteger(attempt) ||+ (isDefined(nextPageUrl) && !isNonEmptyString(nextPageUrl))+ ) {+ return { success: false, error: 'Invalid Teams transcript history 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 job: TeamsTranscriptHistoryJobPayload = {+ connectedAccountId,+ runId,+ pageIndex,+ attempt,+ ...(isNonEmptyString(nextPageUrl) ? { nextPageUrl } : {}),+ };++ try {+ return await importPageOrThrow(job);+ } catch (error) {+ if (error instanceof RetryableLogicFunctionError) {+ throw error;+ }++ console.error(+ `[teams] failed transcript history page ${job.pageIndex} of run ${job.runId} for connected account ${job.connectedAccountId}: ${toErrorMessage(error)}`,+ );++ try {+ return await retryOrFailPageOrThrow({ job, error });+ } catch (recoveryError) {+ if (recoveryError instanceof RetryableLogicFunctionError) {+ throw recoveryError;+ }++ throw new RetryableLogicFunctionError(+ `Could not record the failure of Teams transcript history page ${job.pageIndex}: ${toErrorMessage(recoveryError)}`,+ );+ }+ }+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription.tsindex 48f4554f7ac..409b9cf179a 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/register-teams-transcript-subscription.ts@@ -1,9 +1,8 @@import { isNonEmptyString } from '@sniptt/guards';-import { getConnection, kv, listConnections } from 'twenty-sdk/logic-function';+import { getConnection, kv } from 'twenty-sdk/logic-function';import { isDefined } from 'twenty-sdk/utils';import { FEATURE_FLAGS } from 'src/constants/feature-flags';-import { TEAMS_PROVIDER_NAME } from 'src/features/transcripts/constants/teams-provider-name';import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';import { type TeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/types/teams-transcript-subscription.type';@@ -12,6 +11,7 @@ import { buildTeamsTranscriptsConnectionKvKey } from 'src/features/transcripts/limport { buildTeamsTranscriptsWebhookUrl } from 'src/features/transcripts/logic-functions/utils/build-teams-transcripts-webhook-url';import { createTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/create-teams-transcript-subscription';import { deleteTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/delete-teams-transcript-subscription';+import { isTeamsConnectionListed } from 'src/features/transcripts/logic-functions/utils/is-teams-connection-listed';import { renewTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/renew-teams-transcript-subscription';import { unregisterTeamsTranscriptSubscription } from 'src/features/transcripts/logic-functions/utils/unregister-teams-transcript-subscription';import { isFeatureEnabled } from 'src/utils/is-feature-enabled';@@ -44,13 +44,6 @@ const renewStoredSubscriptionOrUndefined = async ({}};-const isTeamsConnectionListed = async (- connectedAccountId: string,-): Promise<boolean> =>- (await listConnections({ providerName: TEAMS_PROVIDER_NAME })).some(- (connection) => connection.id === connectedAccountId,- );-export const registerTeamsTranscriptSubscription = async ({connectedAccountId,}: {diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-initial-import-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-initial-import-or-throw.tsnew file mode 100644index 00000000000..1fa4872d03d--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-initial-import-or-throw.ts@@ -0,0 +1,73 @@+import { randomBytes } from 'node:crypto';+import { kv } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { FEATURE_FLAGS } from 'src/constants/feature-flags';+import { TEAMS_TRANSCRIPT_HISTORY_INITIAL_IMPORT_DAYS } from 'src/features/transcripts/constants/teams-transcript-history-initial-import-days';+import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transcripts/constants/transcripts-enabled-application-variable-key';+import { MILLISECONDS_PER_DAY } from 'src/features/transcripts/logic-functions/constants/milliseconds-per-day';+import { type TeamsTranscriptHistoryState } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-state.type';+import { buildTeamsTranscriptHistoryKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-history-kv-key';+import { deleteTeamsTranscriptHistoryKvKeys } from 'src/features/transcripts/logic-functions/utils/delete-teams-transcript-history-kv-keys';+import { enqueueTeamsTranscriptHistoryJobOrThrow } from 'src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-history-job-or-throw';+import { isTeamsConnectionListed } from 'src/features/transcripts/logic-functions/utils/is-teams-connection-listed';+import { isTeamsTranscriptHistoryStalled } from 'src/features/transcripts/logic-functions/utils/is-teams-transcript-history-stalled';+import { isFeatureEnabled } from 'src/utils/is-feature-enabled';++export const startTeamsTranscriptHistoryInitialImportOrThrow = async ({+ connectedAccountId,+}: {+ connectedAccountId: string;+}): Promise<void> => {+ if (+ !isFeatureEnabled({+ isAvailable: FEATURE_FLAGS.IS_TRANSCRIPT_IMPORT_ENABLED,+ settingValue: process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY],+ })+ ) {+ return;+ }++ const stateKvKey = buildTeamsTranscriptHistoryKvKey(connectedAccountId);+ const existingState = await kv.get<TeamsTranscriptHistoryState>(stateKvKey);+ const now = Date.now();++ if (+ isDefined(existingState) &&+ existingState.phase !== 'failed' &&+ !isTeamsTranscriptHistoryStalled({ state: existingState, now })+ ) {+ return;+ }++ const state: TeamsTranscriptHistoryState = {+ runId: randomBytes(8).toString('hex'),+ windowStart: new Date(+ now - TEAMS_TRANSCRIPT_HISTORY_INITIAL_IMPORT_DAYS * MILLISECONDS_PER_DAY,+ ).toISOString(),+ windowEnd: new Date(now).toISOString(),+ phase: 'importing',+ pageCount: 0,+ updatedAt: new Date(now).toISOString(),+ };++ await kv.set(stateKvKey, state);++ try {+ await enqueueTeamsTranscriptHistoryJobOrThrow({+ job: { connectedAccountId, runId: state.runId, pageIndex: 0, attempt: 0 },+ delayMilliseconds: 0,+ });+ } catch (error) {+ await kv.set<TeamsTranscriptHistoryState>(stateKvKey, {+ ...state,+ phase: 'failed',+ });++ throw error;+ }++ if (!(await isTeamsConnectionListed(connectedAccountId))) {+ await deleteTeamsTranscriptHistoryKvKeys({ connectedAccountId });+ }+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-call-recording-data.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-call-recording-data.tsnew file mode 100644index 00000000000..6450246b600--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-call-recording-data.ts@@ -0,0 +1,14 @@+import { isDefined } from 'twenty-sdk/utils';++import { type CallRecordingSyncFields } from 'src/features/transcripts/logic-functions/types/call-recording-sync-fields.type';++export const toCallRecordingData = ({+ transcript,+ ...fields+}: CallRecordingSyncFields) =>+ isDefined(transcript)+ ? {+ ...fields,+ transcript: transcript as unknown as Record<string, unknown>,+ }+ : fields;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw.tsindex ac34cafd419..68cf596c9b7 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw.ts@@ -2,6 +2,7 @@ import { type CoreApiClient } from 'twenty-client-sdk/core';import { isDefined } from 'twenty-sdk/utils';import { type CallRecordingSyncFields } from 'src/features/transcripts/logic-functions/types/call-recording-sync-fields.type';+import { toCallRecordingData } from 'src/features/transcripts/logic-functions/utils/to-call-recording-data';const doesCallRecordingMatchOrThrow = async ({coreApiClient,@@ -23,17 +24,6 @@ const doesCallRecordingMatchOrThrow = async ({return isDefined(queryResult.callRecordings?.edges?.[0]?.node);};-const toCallRecordingData = ({- transcript,- ...fields-}: CallRecordingSyncFields) =>- isDefined(transcript)- ? {- ...fields,- transcript: transcript as unknown as Record<string, unknown>,- }- : fields;-const updateCallRecordingOrThrow = async ({coreApiClient,callRecordingId,