The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Count and import older Teams transcripts on request (#27678)
nitina03bc70b537b
diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-count-route-path.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-count-route-path.tsnew file mode 100644index 00000000000..732bb0c175b--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-count-route-path.ts@@ -0,0 +1,2 @@+export const TEAMS_TRANSCRIPT_HISTORY_COUNT_ROUTE_PATH =+ '/teams/transcripts/history/count';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-import-route-path.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-import-route-path.tsnew file mode 100644index 00000000000..d0ca27963f2--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-import-route-path.ts@@ -0,0 +1,2 @@+export const TEAMS_TRANSCRIPT_HISTORY_IMPORT_ROUTE_PATH =+ '/teams/transcripts/history/import';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-max-days.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-max-days.tsnew file mode 100644index 00000000000..d87c8c11822--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-max-days.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_HISTORY_MAX_DAYS = 365;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-status-route-path.ts b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-status-route-path.tsnew file mode 100644index 00000000000..9f797c201e2--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/constants/teams-transcript-history-status-route-path.ts@@ -0,0 +1,2 @@+export const TEAMS_TRANSCRIPT_HISTORY_STATUS_ROUTE_PATH =+ '/teams/transcripts/history/status';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 9e97d23a655..6a757519179 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@@ -24,3 +24,15 @@ export const TEAMS_UNINSTALL_UNIVERSAL_IDENTIFIER =export const TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER ='ff766fbb-0c55-45db-97ee-590aeb5b87a6';++export const TEAMS_COUNT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER =+ '1a853a42-2366-4344-b6d2-ee2a00a1ccb4';++export const TEAMS_TRANSCRIPT_HISTORY_COUNT_UNIVERSAL_IDENTIFIER =+ '844cc01c-b44f-4c80-9953-35320cd5e372';++export const TEAMS_TRANSCRIPT_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER =+ '566dc54f-5de2-40ac-ad13-87051b6f48f8';++export const TEAMS_TRANSCRIPT_HISTORY_STATUS_UNIVERSAL_IDENTIFIER =+ '4b39d2ea-7b16-4e68-a93c-bfb628ae5431';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/__tests__/teams-transcript-history-routes.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/__tests__/teams-transcript-history-routes.test.tsnew file mode 100644index 00000000000..69dcf6fddf1--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/__tests__/teams-transcript-history-routes.test.ts@@ -0,0 +1,208 @@+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 { teamsTranscriptHistoryCountHandler } from 'src/features/transcripts/logic-functions/teams-transcript-history-count';+import { teamsTranscriptHistoryImportHandler } from 'src/features/transcripts/logic-functions/teams-transcript-history-import';+import { teamsTranscriptHistoryStatusHandler } from 'src/features/transcripts/logic-functions/teams-transcript-history-status';++const { kvStore, listConnectionsMock, enqueueJobsMock } = vi.hoisted(() => ({+ kvStore: new Map<string, unknown>(),+ listConnectionsMock: vi.fn(),+ enqueueJobsMock: 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);+ },+ },+ listConnections: listConnectionsMock,+ enqueueJobs: enqueueJobsMock,+}));++const STATE_KV_KEY = 'teams-transcript-history:admin-connection';++const OWNER_CONTEXT = { userWorkspaceId: 'admin' };++const ADMIN_CONNECTION = {+ id: 'admin-connection',+ providerName: 'microsoft-teams',+ name: 'Admin',+ handle: '[email protected]',+ visibility: 'workspace' as const,+ userWorkspaceId: 'admin',+ workspaceMemberId: null,+ accessToken: 'token',+ scopes: [],+ authFailedAt: null,+ authFailedReason: null,+};++const buildRoutePayload = <TBody>(body: TBody) => ({+ headers: {},+ queryStringParameters: {},+ pathParameters: {},+ body,+ isBase64Encoded: false,+ requestContext: { http: { method: 'POST', path: '/' } },+ userWorkspaceId: null,+});++const COUNTED_STATE = {+ runId: 'counted-run',+ days: 90,+ windowStart: '2026-06-17T00:00:00.000Z',+ windowEnd: '2026-09-15T00:00:00.000Z',+ phase: 'counted',+ transcriptCount: 8,+ alreadyImportedCount: 2,+ deletedCount: 1,+ pageCount: 3,+ importedCount: 0,+ skippedCount: 0,+ unavailableCount: 0,+ updatedAt: '2026-09-15T00:05:00.000Z',+};++describe('Teams transcript history routes', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ kvStore.clear();+ process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY] = 'true';+ listConnectionsMock.mockResolvedValue([ADMIN_CONNECTION]);+ enqueueJobsMock.mockResolvedValue(undefined);+ });++ it.each([0, 366, 1.5, '30', undefined])(+ 'should refuse to count %s days',+ async (days) => {+ await expect(+ teamsTranscriptHistoryCountHandler(+ buildRoutePayload({ days }),+ OWNER_CONTEXT,+ ),+ ).resolves.toEqual({ success: false, errorCode: 'invalid-days' });+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ },+ );++ it('should count on the connection the member added', async () => {+ await expect(+ teamsTranscriptHistoryCountHandler(+ buildRoutePayload({ days: 90 }),+ OWNER_CONTEXT,+ ),+ ).resolves.toMatchObject({+ success: true,+ state: { phase: 'counting', days: 90 },+ });+ expect(enqueueJobsMock).toHaveBeenCalledTimes(1);+ });++ it.each([+ ['a member who did not add the shared connection', 'member'],+ ['a request without a user', null],+ ])(+ 'should not let %s use the shared connection',+ async (_, userWorkspaceId) => {+ await expect(+ teamsTranscriptHistoryCountHandler(buildRoutePayload({ days: 90 }), {+ userWorkspaceId,+ }),+ ).resolves.toEqual({ success: false, errorCode: 'not-connected' });+ await expect(+ teamsTranscriptHistoryImportHandler(+ buildRoutePayload({ runId: 'counted-run' }),+ { userWorkspaceId },+ ),+ ).resolves.toEqual({ success: false, errorCode: 'not-connected' });+ expect(enqueueJobsMock).not.toHaveBeenCalled();+ },+ );++ it('should refuse a count while another run is active and accept one once it stalled', async () => {+ kvStore.set(STATE_KV_KEY, {+ ...COUNTED_STATE,+ phase: 'importing',+ updatedAt: new Date().toISOString(),+ });++ await expect(+ teamsTranscriptHistoryCountHandler(+ buildRoutePayload({ days: 90 }),+ OWNER_CONTEXT,+ ),+ ).resolves.toEqual({ success: false, errorCode: 'run-already-active' });++ kvStore.set(STATE_KV_KEY, {+ ...COUNTED_STATE,+ phase: 'importing',+ updatedAt: new Date(Date.now() - 41 * 60 * 1_000).toISOString(),+ });++ await expect(+ teamsTranscriptHistoryCountHandler(+ buildRoutePayload({ days: 90 }),+ OWNER_CONTEXT,+ ),+ ).resolves.toMatchObject({ success: true, state: { phase: 'counting' } });+ });++ it.each([+ ['without a run id', {}],+ ['for another run', { runId: 'other-run' }],+ ])('should ask for a count before importing %s', async (_, body) => {+ kvStore.set(STATE_KV_KEY, COUNTED_STATE);++ await expect(+ teamsTranscriptHistoryImportHandler(+ buildRoutePayload(body),+ OWNER_CONTEXT,+ ),+ ).resolves.toEqual({ success: false, errorCode: 'count-required' });+ });++ it('should keep the count when the import cannot be scheduled', async () => {+ kvStore.set(STATE_KV_KEY, COUNTED_STATE);+ enqueueJobsMock.mockRejectedValue(new Error('Queue unavailable'));+ vi.spyOn(console, 'error').mockImplementation(() => undefined);++ await expect(+ teamsTranscriptHistoryImportHandler(+ buildRoutePayload({ runId: 'counted-run' }),+ OWNER_CONTEXT,+ ),+ ).resolves.toEqual({ success: false, errorCode: 'unknown' });+ expect(kvStore.get(STATE_KV_KEY)).toEqual(COUNTED_STATE);+ });++ it('should not return the next page job with the status', async () => {+ kvStore.set(STATE_KV_KEY, {+ ...COUNTED_STATE,+ phase: 'importing',+ updatedAt: new Date().toISOString(),+ nextJob: {+ connectedAccountId: 'admin-connection',+ runId: 'counted-run',+ chunkIndex: 0,+ pageIndex: 1,+ attempt: 0,+ },+ });++ const result = await teamsTranscriptHistoryStatusHandler(+ buildRoutePayload(null),+ OWNER_CONTEXT,+ );++ expect(result).toMatchObject({ success: true, isStalled: false });+ expect(result.success && result.state).not.toHaveProperty('nextJob');+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-chunk-days.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-chunk-days.tsnew file mode 100644index 00000000000..bede6e03f53--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-chunk-days.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_HISTORY_CHUNK_DAYS = 31;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-initial-import-kv-key-prefix.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-initial-import-kv-key-prefix.tsnew file mode 100644index 00000000000..70ed415cd0e--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-initial-import-kv-key-prefix.ts@@ -0,0 +1,2 @@+export const TEAMS_TRANSCRIPT_HISTORY_INITIAL_IMPORT_KV_KEY_PREFIX =+ 'teams-transcript-history-initial-import';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-max-pages.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-max-pages.tsnew file mode 100644index 00000000000..040acbbf114--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-history-max-pages.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_HISTORY_MAX_PAGES = 500;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-count-transcript-history.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-count-transcript-history.tsnew file mode 100644index 00000000000..89588f7ee56--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-count-transcript-history.ts@@ -0,0 +1,19 @@+import { defineLogicFunction } from 'twenty-sdk/define';++import { TEAMS_COUNT_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 teamsCountTranscriptHistoryHandler = (+ payload: Partial<Record<keyof TeamsTranscriptHistoryJobPayload, unknown>>,+) => processTeamsTranscriptHistoryPageOrThrow({ phase: 'counting', payload });++export default defineLogicFunction({+ universalIdentifier: TEAMS_COUNT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER,+ name: 'teams-count-transcript-history',+ description:+ 'Counts the Teams transcripts on one calendar page of a history import window, and how many are already in Twenty, then queues the next page.',+ timeoutSeconds: TEAMS_IMPORT_TRANSCRIPT_HISTORY_TIMEOUT_SECONDS,+ handler: teamsCountTranscriptHistoryHandler,+});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.tsindex 8d48bbe0401..7c107db1647 100644--- 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.ts@@ -7,7 +7,7 @@ import { processTeamsTranscriptHistoryPageOrThrow } from 'src/features/transcripexport const teamsImportTranscriptHistoryHandler = (payload: Partial<Record<keyof TeamsTranscriptHistoryJobPayload, unknown>>,-) => processTeamsTranscriptHistoryPageOrThrow(payload);+) => processTeamsTranscriptHistoryPageOrThrow({ phase: 'importing', payload });export default defineLogicFunction({universalIdentifier: TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER,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 94f33926cef..d47064fa3c3 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@@ -84,7 +84,7 @@ export const teamsListOrganizerTranscriptsHandler = async (accessToken: connection.accessToken,url: calendarPageUrl,});- const transcripts = await listTeamsOccurrenceTranscripts({+ const { transcripts } = await listTeamsOccurrenceTranscripts({accessToken: connection.accessToken,occurrences: page.occurrences,});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-count.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-count.tsnew file mode 100644index 00000000000..5c9ebe49c9b--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-count.ts@@ -0,0 +1,48 @@+import { isPositiveInteger } from '@sniptt/guards';+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';++import { TEAMS_TRANSCRIPT_HISTORY_COUNT_ROUTE_PATH } from 'src/features/transcripts/constants/teams-transcript-history-count-route-path';+import { TEAMS_TRANSCRIPT_HISTORY_MAX_DAYS } from 'src/features/transcripts/constants/teams-transcript-history-max-days';+import { TEAMS_TRANSCRIPT_HISTORY_COUNT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import { type TeamsTranscriptHistoryRouteResult } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type';+import { handleTeamsTranscriptHistoryRoute } from 'src/features/transcripts/logic-functions/utils/handle-teams-transcript-history-route';+import { startTeamsTranscriptHistoryCountOrThrow } from 'src/features/transcripts/logic-functions/utils/start-teams-transcript-history-count-or-throw';++export const teamsTranscriptHistoryCountHandler = (+ routePayload: RoutePayload<{ days?: unknown }>,+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<TeamsTranscriptHistoryRouteResult> =>+ handleTeamsTranscriptHistoryRoute({+ context,+ failureLogMessage: 'failed to start counting transcript history',+ handle: async (connectedAccountId) => {+ const days = routePayload.body?.days;++ if (+ !isPositiveInteger(days) ||+ days > TEAMS_TRANSCRIPT_HISTORY_MAX_DAYS+ ) {+ return { success: false, errorCode: 'invalid-days' };+ }++ return startTeamsTranscriptHistoryCountOrThrow({+ connectedAccountId,+ days,+ });+ },+ });++export default defineLogicFunction({+ universalIdentifier: TEAMS_TRANSCRIPT_HISTORY_COUNT_UNIVERSAL_IDENTIFIER,+ name: 'teams-transcript-history-count',+ description:+ 'Starts counting the Teams transcripts of the connection the requesting user added, over the last given number of days, before importing them.',+ timeoutSeconds: 30,+ handler: teamsTranscriptHistoryCountHandler,+ httpRouteTriggerSettings: {+ path: TEAMS_TRANSCRIPT_HISTORY_COUNT_ROUTE_PATH,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-import.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-import.tsnew file mode 100644index 00000000000..3819b2c3c3b--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-import.ts@@ -0,0 +1,44 @@+import { isNonEmptyString } from '@sniptt/guards';+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';++import { TEAMS_TRANSCRIPT_HISTORY_IMPORT_ROUTE_PATH } from 'src/features/transcripts/constants/teams-transcript-history-import-route-path';+import { TEAMS_TRANSCRIPT_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import { type TeamsTranscriptHistoryRouteResult } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type';+import { handleTeamsTranscriptHistoryRoute } from 'src/features/transcripts/logic-functions/utils/handle-teams-transcript-history-route';+import { startTeamsTranscriptHistoryImportFromCountOrThrow } from 'src/features/transcripts/logic-functions/utils/start-teams-transcript-history-import-from-count-or-throw';++export const teamsTranscriptHistoryImportHandler = (+ routePayload: RoutePayload<{ runId?: unknown }>,+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<TeamsTranscriptHistoryRouteResult> =>+ handleTeamsTranscriptHistoryRoute({+ context,+ failureLogMessage: 'failed to start importing transcript history',+ handle: async (connectedAccountId) => {+ const runId = routePayload.body?.runId;++ if (!isNonEmptyString(runId)) {+ return { success: false, errorCode: 'count-required' };+ }++ return startTeamsTranscriptHistoryImportFromCountOrThrow({+ connectedAccountId,+ runId,+ });+ },+ });++export default defineLogicFunction({+ universalIdentifier: TEAMS_TRANSCRIPT_HISTORY_IMPORT_UNIVERSAL_IDENTIFIER,+ name: 'teams-transcript-history-import',+ description:+ 'Starts importing the Teams transcripts counted for the connection the requesting user added, waiting a minute after each calendar page that imported transcripts.',+ timeoutSeconds: 30,+ handler: teamsTranscriptHistoryImportHandler,+ httpRouteTriggerSettings: {+ path: TEAMS_TRANSCRIPT_HISTORY_IMPORT_ROUTE_PATH,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-status.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-status.tsnew file mode 100644index 00000000000..e704710fce2--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/teams-transcript-history-status.ts@@ -0,0 +1,54 @@+import { defineLogicFunction, type RoutePayload } from 'twenty-sdk/define';+import {+ kv,+ type LogicFunctionExecutionContext,+} from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { TEAMS_TRANSCRIPT_HISTORY_STATUS_ROUTE_PATH } from 'src/features/transcripts/constants/teams-transcript-history-status-route-path';+import { TEAMS_TRANSCRIPT_HISTORY_STATUS_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import { type TeamsTranscriptHistoryRouteResult } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type';+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 { handleTeamsTranscriptHistoryRoute } from 'src/features/transcripts/logic-functions/utils/handle-teams-transcript-history-route';+import { isTeamsTranscriptHistoryStalled } from 'src/features/transcripts/logic-functions/utils/is-teams-transcript-history-stalled';++export const teamsTranscriptHistoryStatusHandler = (+ _routePayload: RoutePayload,+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+): Promise<TeamsTranscriptHistoryRouteResult> =>+ handleTeamsTranscriptHistoryRoute({+ context,+ failureLogMessage: 'failed to read transcript history status',+ handle: async (connectedAccountId) => {+ const state = await kv.get<TeamsTranscriptHistoryState>(+ buildTeamsTranscriptHistoryKvKey(connectedAccountId),+ );++ if (!isDefined(state)) {+ return { success: true, state: null, isStalled: false };+ }++ const { nextJob: _nextJob, ...routeState } = state;++ return {+ success: true,+ state: routeState,+ isStalled: isTeamsTranscriptHistoryStalled({ state, now: Date.now() }),+ };+ },+ });++export default defineLogicFunction({+ universalIdentifier: TEAMS_TRANSCRIPT_HISTORY_STATUS_UNIVERSAL_IDENTIFIER,+ name: 'teams-transcript-history-status',+ description:+ 'Returns the progress of the Teams transcript history count or import of the connection the requesting user added.',+ timeoutSeconds: 15,+ handler: teamsTranscriptHistoryStatusHandler,+ httpRouteTriggerSettings: {+ path: TEAMS_TRANSCRIPT_HISTORY_STATUS_ROUTE_PATH,+ httpMethod: 'POST',+ isAuthRequired: true,+ },+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-connection-unavailable-error.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-connection-unavailable-error.tsnew file mode 100644index 00000000000..106706958ce--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-connection-unavailable-error.ts@@ -0,0 +1,15 @@+export class TeamsConnectionUnavailableError extends Error {+ readonly code: 'not-connected' | 'reconnect-required';++ constructor({+ message,+ code,+ }: {+ message: string;+ code: 'not-connected' | 'reconnect-required';+ }) {+ super(message);+ this.name = 'TeamsConnectionUnavailableError';+ this.code = code;+ }+}diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-error-code.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-error-code.type.tsnew file mode 100644index 00000000000..441437a67c4--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-error-code.type.ts@@ -0,0 +1,5 @@+export type TeamsTranscriptHistoryErrorCode =+ | 'reconnect-required'+ | 'transcripts-disabled-by-admin'+ | 'page-limit-reached'+ | 'unknown';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.tsindex 08f6f37a54e..b6dae3de29a 100644--- 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.ts@@ -1,6 +1,7 @@export type TeamsTranscriptHistoryJobPayload = {connectedAccountId: string;runId: string;+ chunkIndex: number;pageIndex: number;attempt: number;nextPageUrl?: string;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-page-counts.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-page-counts.type.tsnew file mode 100644index 00000000000..b24f5092b11--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-page-counts.type.ts@@ -0,0 +1,11 @@+import { type TeamsTranscriptHistoryState } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-state.type';++export type TeamsTranscriptHistoryPageCounts = Pick<+ TeamsTranscriptHistoryState,+ | 'transcriptCount'+ | 'alreadyImportedCount'+ | 'deletedCount'+ | 'importedCount'+ | 'skippedCount'+ | 'unavailableCount'+>;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-route-error-code.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-route-error-code.type.tsnew file mode 100644index 00000000000..d40b317fca4--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-route-error-code.type.ts@@ -0,0 +1,8 @@+export type TeamsTranscriptHistoryRouteErrorCode =+ | 'transcripts-not-enabled'+ | 'not-connected'+ | 'reconnect-required'+ | 'invalid-days'+ | 'run-already-active'+ | 'count-required'+ | 'unknown';diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type.tsnew file mode 100644index 00000000000..f479949d03d--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type.ts@@ -0,0 +1,10 @@+import { type TeamsTranscriptHistoryRouteErrorCode } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-route-error-code.type';+import { type TeamsTranscriptHistoryState } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-state.type';++export type TeamsTranscriptHistoryRouteResult =+ | {+ success: true;+ state: Omit<TeamsTranscriptHistoryState, 'nextJob'> | null;+ isStalled: boolean;+ }+ | { success: false; errorCode: TeamsTranscriptHistoryRouteErrorCode };diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.type.tsnew file mode 100644index 00000000000..172ea8b79d0--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.type.ts@@ -0,0 +1 @@+export type TeamsTranscriptHistoryRunningPhase = 'counting' | 'importing';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.tsindex 8ee6d6ec381..54c9a3b01a2 100644--- 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.ts@@ -1,11 +1,22 @@+import { type TeamsTranscriptHistoryErrorCode } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-error-code.type';+import { type TeamsTranscriptHistoryRunningPhase } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.type';import { type TeamsTranscriptHistoryJobPayload } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type';export type TeamsTranscriptHistoryState = {runId: string;+ days: number;windowStart: string;windowEnd: string;- phase: 'importing' | 'imported' | 'failed';+ phase: TeamsTranscriptHistoryRunningPhase | 'counted' | 'imported' | 'failed';+ transcriptCount: number;+ alreadyImportedCount: number;+ deletedCount: number;pageCount: number;+ importedCount: number;+ skippedCount: number;+ unavailableCount: number;+ checkedThrough?: string;updatedAt: string;+ errorCode?: TeamsTranscriptHistoryErrorCode;nextJob?: TeamsTranscriptHistoryJobPayload;};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-connection-for-request-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-connection-for-request-or-throw.test.tsnew file mode 100644index 00000000000..9756a307b3e--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-connection-for-request-or-throw.test.ts@@ -0,0 +1,103 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { getTeamsConnectionForRequestOrThrow } from 'src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw';++const { listConnectionsMock } = vi.hoisted(() => ({+ listConnectionsMock: vi.fn(),+}));++vi.mock('twenty-sdk/logic-function', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ listConnections: listConnectionsMock,+}));++const buildConnection = ({+ id,+ visibility,+ userWorkspaceId,+}: {+ id: string;+ visibility: 'user' | 'workspace';+ userWorkspaceId: string;+}) => ({+ id,+ providerName: 'microsoft-teams',+ name: id,+ handle: `${id}@acme.com`,+ visibility,+ userWorkspaceId,+ workspaceMemberId: null,+ accessToken: 'token',+ scopes: [],+ authFailedAt: null,+ authFailedReason: null,+});++const SHARED_CONNECTION = buildConnection({+ id: 'shared-connection',+ visibility: 'workspace',+ userWorkspaceId: 'admin',+});++describe('getTeamsConnectionForRequestOrThrow', () => {+ beforeEach(() => {+ listConnectionsMock.mockResolvedValue([+ SHARED_CONNECTION,+ buildConnection({+ id: 'member-connection',+ visibility: 'user',+ userWorkspaceId: 'member',+ }),+ ]);+ });++ it('should fall back on the workspace-shared connection by default', async () => {+ await expect(+ getTeamsConnectionForRequestOrThrow({ userWorkspaceId: 'other-member' }),+ ).resolves.toMatchObject({ id: 'shared-connection' });+ });++ it.each([+ ['their personal connection', 'member', 'member-connection'],+ [+ 'the workspace-shared connection they added',+ 'admin',+ 'shared-connection',+ ],+ ])(+ 'should give a member who requires their own connection %s',+ async (_, userWorkspaceId, connectionId) => {+ await expect(+ getTeamsConnectionForRequestOrThrow(+ { userWorkspaceId },+ { isOwnConnectionRequired: true },+ ),+ ).resolves.toMatchObject({ id: connectionId });+ },+ );++ it.each([+ ['a member without a connection', 'other-member'],+ ['a request without a user', null],+ ])(+ 'should not hand %s the workspace-shared connection when their own is required',+ async (_, userWorkspaceId) => {+ await expect(+ getTeamsConnectionForRequestOrThrow(+ { userWorkspaceId },+ { isOwnConnectionRequired: true },+ ),+ ).rejects.toMatchObject({ code: 'not-connected' });+ },+ );++ it('should ask to reconnect a connection whose authentication failed', async () => {+ listConnectionsMock.mockResolvedValue([+ { ...SHARED_CONNECTION, authFailedAt: '2026-09-15T00:00:00.000Z' },+ ]);++ await expect(+ getTeamsConnectionForRequestOrThrow({ userWorkspaceId: 'admin' }),+ ).rejects.toMatchObject({ code: 'reconnect-required' });+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-transcript-history-chunk-window.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-transcript-history-chunk-window.test.tsnew file mode 100644index 00000000000..9155e958f23--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-transcript-history-chunk-window.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest';++import { getTeamsTranscriptHistoryChunkWindow } from 'src/features/transcripts/logic-functions/utils/get-teams-transcript-history-chunk-window';++const HISTORY_WINDOW = {+ windowStart: '2026-07-01T00:00:00.000Z',+ windowEnd: '2026-09-15T00:00:00.000Z',+};++describe('getTeamsTranscriptHistoryChunkWindow', () => {+ it('should walk the window in 31-day chunks starting from the newest', () => {+ expect(+ [0, 1, 2].map((chunkIndex) =>+ getTeamsTranscriptHistoryChunkWindow({ ...HISTORY_WINDOW, chunkIndex }),+ ),+ ).toEqual([+ {+ startDateTime: '2026-08-15T00:00:00.000Z',+ endDateTime: '2026-09-15T00:00:00.000Z',+ },+ {+ startDateTime: '2026-07-15T00:00:00.000Z',+ endDateTime: '2026-08-15T00:00:00.000Z',+ },+ {+ startDateTime: '2026-07-01T00:00:00.000Z',+ endDateTime: '2026-07-15T00:00:00.000Z',+ },+ ]);+ });++ it('should return nothing once the chunk starts before the window', () => {+ expect(+ getTeamsTranscriptHistoryChunkWindow({+ ...HISTORY_WINDOW,+ chunkIndex: 3,+ }),+ ).toBeUndefined();+ });++ it('should cover a 31-day window in a single chunk', () => {+ const initialImportWindow = {+ windowStart: '2026-08-15T00:00:00.000Z',+ windowEnd: '2026-09-15T00:00:00.000Z',+ };++ expect(+ getTeamsTranscriptHistoryChunkWindow({+ ...initialImportWindow,+ chunkIndex: 0,+ }),+ ).toEqual({+ startDateTime: initialImportWindow.windowStart,+ endDateTime: initialImportWindow.windowEnd,+ });+ expect(+ getTeamsTranscriptHistoryChunkWindow({+ ...initialImportWindow,+ chunkIndex: 1,+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-transcript-history-page-transition.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-transcript-history-page-transition.test.tsnew file mode 100644index 00000000000..dc25bbad141--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/get-teams-transcript-history-page-transition.test.ts@@ -0,0 +1,162 @@+import { describe, expect, it } from 'vitest';++import { TEAMS_TRANSCRIPT_HISTORY_MAX_PAGES } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-max-pages';+import { getTeamsTranscriptHistoryPageTransition } from 'src/features/transcripts/logic-functions/utils/get-teams-transcript-history-page-transition';++const NOW = Date.parse('2026-09-15T00:05:00.000Z');++const NEXT_PAGE_URL =+ 'https://graph.microsoft.com/v1.0/me/calendarView?$skiptoken=abc';++const STATE = {+ runId: 'a1b2c3d4e5f60718',+ days: 76,+ windowStart: '2026-07-01T00:00:00.000Z',+ windowEnd: '2026-09-15T00:00:00.000Z',+ phase: 'counting' as const,+ transcriptCount: 10,+ alreadyImportedCount: 2,+ deletedCount: 1,+ pageCount: 3,+ importedCount: 0,+ skippedCount: 0,+ unavailableCount: 0,+ checkedThrough: '2026-08-15T00:00:00.000Z',+ updatedAt: '2026-09-15T00:00:00.000Z',+};++const EMPTY_PAGE_COUNTS = {+ transcriptCount: 0,+ alreadyImportedCount: 0,+ deletedCount: 0,+ importedCount: 0,+ skippedCount: 0,+ unavailableCount: 0,+};++const JOB = {+ connectedAccountId: 'connected-account-1',+ runId: STATE.runId,+ chunkIndex: 1,+ pageIndex: 3,+ attempt: 2,+};++describe('getTeamsTranscriptHistoryPageTransition', () => {+ it('should add the page counts and continue on the next calendar page of the chunk', () => {+ expect(+ getTeamsTranscriptHistoryPageTransition({+ state: STATE,+ job: JOB,+ phase: 'counting',+ pageCounts: {+ ...EMPTY_PAGE_COUNTS,+ transcriptCount: 5,+ alreadyImportedCount: 1,+ deletedCount: 1,+ },+ nextPageUrl: NEXT_PAGE_URL,+ now: NOW,+ }),+ ).toEqual({+ state: {+ ...STATE,+ transcriptCount: 15,+ alreadyImportedCount: 3,+ deletedCount: 2,+ pageCount: 4,+ updatedAt: '2026-09-15T00:05:00.000Z',+ },+ nextJob: {+ ...JOB,+ pageIndex: 4,+ attempt: 0,+ nextPageUrl: NEXT_PAGE_URL,+ },+ });+ });++ it('should mark the chunk as checked and move to the older chunk after its last page', () => {+ expect(+ getTeamsTranscriptHistoryPageTransition({+ state: STATE,+ job: { ...JOB, nextPageUrl: NEXT_PAGE_URL },+ phase: 'counting',+ pageCounts: EMPTY_PAGE_COUNTS,+ now: NOW,+ }),+ ).toEqual({+ state: {+ ...STATE,+ pageCount: 4,+ checkedThrough: '2026-07-15T00:00:00.000Z',+ updatedAt: '2026-09-15T00:05:00.000Z',+ },+ nextJob: {+ connectedAccountId: JOB.connectedAccountId,+ runId: JOB.runId,+ chunkIndex: 2,+ pageIndex: 4,+ attempt: 0,+ },+ });+ });++ it('should complete the count after the last page of the oldest chunk', () => {+ const transition = getTeamsTranscriptHistoryPageTransition({+ state: STATE,+ job: { ...JOB, chunkIndex: 2 },+ phase: 'counting',+ pageCounts: EMPTY_PAGE_COUNTS,+ now: NOW,+ });++ expect(transition.nextJob).toBeUndefined();+ expect(transition.state).toMatchObject({+ phase: 'counted',+ checkedThrough: '2026-07-01T00:00:00.000Z',+ });+ });++ it('should complete the import after the last page of the oldest chunk', () => {+ const transition = getTeamsTranscriptHistoryPageTransition({+ state: { ...STATE, phase: 'importing' },+ job: { ...JOB, chunkIndex: 2 },+ phase: 'importing',+ pageCounts: {+ ...EMPTY_PAGE_COUNTS,+ importedCount: 4,+ skippedCount: 2,+ unavailableCount: 1,+ },+ now: NOW,+ });++ expect(transition.nextJob).toBeUndefined();+ expect(transition.state).toMatchObject({+ phase: 'imported',+ transcriptCount: 10,+ importedCount: 4,+ skippedCount: 2,+ unavailableCount: 1,+ checkedThrough: '2026-07-01T00:00:00.000Z',+ });+ });++ it('should fail the run instead of completing it at the page limit', () => {+ const transition = getTeamsTranscriptHistoryPageTransition({+ state: { ...STATE, pageCount: TEAMS_TRANSCRIPT_HISTORY_MAX_PAGES - 1 },+ job: { ...JOB, pageIndex: TEAMS_TRANSCRIPT_HISTORY_MAX_PAGES - 1 },+ phase: 'counting',+ pageCounts: EMPTY_PAGE_COUNTS,+ nextPageUrl: NEXT_PAGE_URL,+ now: NOW,+ });++ expect(transition.nextJob).toBeUndefined();+ expect(transition.state).toMatchObject({+ phase: 'failed',+ errorCode: 'page-limit-reached',+ });+ });+});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.tsindex 60549011650..2d15a1b9ddc 100644--- 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.ts@@ -22,6 +22,8 @@ vi.mock(}),);+const RUN_STARTED_AT = '2026-09-15T00:00:00.000Z';+const TRANSCRIPT_CONTENT = ['WEBVTT','',@@ -42,6 +44,7 @@ const buildTranscript = (transcriptId: string) => ({type CallRecordingRow = {id: string;status: string;+ createdAt: string;deletedAt: string | null;};@@ -98,7 +101,12 @@ const buildCoreApiClient = (rows: CallRecordingRow[]) => {};}) => {for (const { id, status } of request.createCallRecordings.__args.data) {- rowsById.set(id, { id, status, deletedAt: null });+ rowsById.set(id, {+ id,+ status,+ createdAt: '2026-09-15T00:02:00.000Z',+ deletedAt: null,+ });}return {};@@ -125,13 +133,31 @@ const getWrittenTranscriptIds = (const buildRow = (transcriptId: string,status: string,- deletedAt: string | null = null,+ {+ createdAt = '2026-08-01T00:00:00.000Z',+ deletedAt = null,+ }: { createdAt?: string; deletedAt?: string | null } = {},): CallRecordingRow => ({id: computeCallRecordingIdForTeamsTranscript(transcriptId),status,+ createdAt,deletedAt,});+const toPageCounts = (+ counts: Partial<+ Record<'importedCount' | 'skippedCount' | 'unavailableCount', number>+ >,+) => ({+ transcriptCount: 0,+ alreadyImportedCount: 0,+ deletedCount: 0,+ importedCount: 0,+ skippedCount: 0,+ unavailableCount: 0,+ ...counts,+});+describe('importTeamsTranscriptHistoryPageOrThrow', () => {beforeEach(() => {vi.clearAllMocks();@@ -142,7 +168,9 @@ describe('importTeamsTranscriptHistoryPageOrThrow', () => {const transcriptIds = ['completed', 'deleted', 'processing', 'new'];const coreApiClient = buildCoreApiClient([buildRow('completed', 'COMPLETED'),- buildRow('deleted', 'COMPLETED', '2026-09-02T00:00:00.000Z'),+ buildRow('deleted', 'COMPLETED', {+ deletedAt: '2026-09-02T00:00:00.000Z',+ }),buildRow('processing', 'PROCESSING'),]);@@ -151,9 +179,10 @@ describe('importTeamsTranscriptHistoryPageOrThrow', () => {accessToken: 'token',coreApiClient,transcripts: transcriptIds.map(buildTranscript),+ importedSince: RUN_STARTED_AT,isRunActive: async () => true,}),- ).resolves.toBe(2);+ ).resolves.toEqual(toPageCounts({ importedCount: 2, skippedCount: 2 }));expect(getWrittenTranscriptIds(coreApiClient, transcriptIds)).toEqual(['processing','new',@@ -170,11 +199,9 @@ describe('importTeamsTranscriptHistoryPageOrThrow', () => {downloadMeetingTranscriptContentMock.mockImplementation(async () => {coreApiClient.rowsById.set(computeCallRecordingIdForTeamsTranscript('deleted-during-import'),- buildRow(- 'deleted-during-import',- 'PROCESSING',- '2026-09-15T00:01:00.000Z',- ),+ buildRow('deleted-during-import', 'PROCESSING', {+ deletedAt: '2026-09-15T00:01:00.000Z',+ }),);return TRANSCRIPT_CONTENT;@@ -185,9 +212,32 @@ describe('importTeamsTranscriptHistoryPageOrThrow', () => {accessToken: 'token',coreApiClient,transcripts: transcriptIds.map(buildTranscript),+ importedSince: RUN_STARTED_AT,+ isRunActive: async () => true,+ }),+ ).resolves.toEqual(toPageCounts({ importedCount: 1, skippedCount: 1 }));+ expect(getWrittenTranscriptIds(coreApiClient, transcriptIds)).toEqual([+ 'new',+ ]);+ });++ it('should count recordings a failed attempt of the page already wrote as imported', async () => {+ const transcriptIds = ['written-by-failed-attempt', 'new'];+ const coreApiClient = buildCoreApiClient([+ buildRow('written-by-failed-attempt', 'COMPLETED', {+ createdAt: RUN_STARTED_AT,+ }),+ ]);++ await expect(+ importTeamsTranscriptHistoryPageOrThrow({+ accessToken: 'token',+ coreApiClient,+ transcripts: transcriptIds.map(buildTranscript),+ importedSince: RUN_STARTED_AT,isRunActive: async () => true,}),- ).resolves.toBe(1);+ ).resolves.toEqual(toPageCounts({ importedCount: 2 }));expect(getWrittenTranscriptIds(coreApiClient, transcriptIds)).toEqual(['new',]);@@ -212,9 +262,10 @@ describe('importTeamsTranscriptHistoryPageOrThrow', () => {accessToken: 'token',coreApiClient,transcripts: transcriptIds.map(buildTranscript),+ importedSince: RUN_STARTED_AT,isRunActive: async () => true,}),- ).resolves.toBe(1);+ ).resolves.toEqual(toPageCounts({ importedCount: 1, unavailableCount: 2 }));expect(getWrittenTranscriptIds(coreApiClient, transcriptIds)).toEqual(['new',]);@@ -234,6 +285,7 @@ describe('importTeamsTranscriptHistoryPageOrThrow', () => {accessToken: 'token',coreApiClient: buildCoreApiClient([]),transcripts: [buildTranscript('new')],+ importedSince: RUN_STARTED_AT,isRunActive: async () => true,}),).rejects.toThrow('503');@@ -251,9 +303,10 @@ describe('importTeamsTranscriptHistoryPageOrThrow', () => {accessToken: 'token',coreApiClient,transcripts: transcriptIds.map(buildTranscript),+ importedSince: RUN_STARTED_AT,isRunActive: async () => true,}),- ).resolves.toBe(11);+ ).resolves.toEqual(toPageCounts({ importedCount: 11 }));expect(coreApiClient.mutation).toHaveBeenCalledTimes(2);expect(coreApiClient.rowsById.size).toBe(11);});@@ -272,9 +325,10 @@ describe('importTeamsTranscriptHistoryPageOrThrow', () => {transcripts: Array.from({ length: 11 }, (_, index) =>buildTranscript(`new-${index}`),),+ importedSince: RUN_STARTED_AT,isRunActive,}),- ).resolves.toBe(10);+ ).resolves.toEqual(toPageCounts({ importedCount: 10 }));expect(coreApiClient.mutation).toHaveBeenCalledTimes(1);});});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/is-teams-meeting-occurrence-starting-in-window.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/is-teams-meeting-occurrence-starting-in-window.test.tsnew file mode 100644index 00000000000..6c584bcc26d--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/is-teams-meeting-occurrence-starting-in-window.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';++import { isTeamsMeetingOccurrenceStartingInWindow } from 'src/features/transcripts/logic-functions/utils/is-teams-meeting-occurrence-starting-in-window';++const NEWER_CHUNK = {+ startDateTime: '2026-08-16T00:00:00.000Z',+ endDateTime: '2026-09-15T00:00:00.000Z',+};++const OLDER_CHUNK = {+ startDateTime: '2026-07-17T00:00:00.000Z',+ endDateTime: '2026-08-16T00:00:00.000Z',+};++describe('isTeamsMeetingOccurrenceStartingInWindow', () => {+ it('should give an occurrence spanning a chunk boundary only to the chunk it starts in', () => {+ const occurrence = { startDateTime: '2026-08-15T23:30:00.000Z' };++ expect(+ isTeamsMeetingOccurrenceStartingInWindow({+ occurrence,+ window: OLDER_CHUNK,+ }),+ ).toBe(true);+ expect(+ isTeamsMeetingOccurrenceStartingInWindow({+ occurrence,+ window: NEWER_CHUNK,+ }),+ ).toBe(false);+ });++ it('should include the window start and exclude its end', () => {+ const occurrence = { startDateTime: '2026-08-16T00:00:00.000Z' };++ expect(+ isTeamsMeetingOccurrenceStartingInWindow({+ occurrence,+ window: NEWER_CHUNK,+ }),+ ).toBe(true);+ expect(+ isTeamsMeetingOccurrenceStartingInWindow({+ occurrence,+ window: OLDER_CHUNK,+ }),+ ).toBe(false);+ });+});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.tsindex cb22f410d22..a1310f79262 100644--- 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.ts@@ -47,7 +47,7 @@ describe('listTeamsOccurrenceTranscripts', () => {{ id: 'other-week', createdDateTime: '2026-09-15T10:05:00Z' },]);- const transcripts = await listTeamsOccurrenceTranscripts({+ const { transcripts } = await listTeamsOccurrenceTranscripts({accessToken: 'token',occurrences: WEEKLY_SYNC_OCCURRENCES,});@@ -77,17 +77,19 @@ describe('listTeamsOccurrenceTranscripts', () => {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'),- ],- });+ const { transcripts, unavailableMeetingCount } =+ await listTeamsOccurrenceTranscripts({+ accessToken: 'token',+ occurrences: [+ ...WEEKLY_SYNC_OCCURRENCES,+ buildOccurrence('standup', '2026-09-02T09:00:00.000Z'),+ ],+ });expect(transcripts.map(({ transcript }) => transcript.id)).toEqual(['standup',]);+ expect(unavailableMeetingCount).toBe(1);});it('should fail when Microsoft Graph fails for another reason', async () => {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.tsindex 258a48b42b4..e33731bcacc 100644--- 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.ts@@ -2,7 +2,9 @@ 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 { TEAMS_COUNT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';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';import { processTeamsTranscriptHistoryPageOrThrow } from 'src/features/transcripts/logic-functions/utils/process-teams-transcript-history-page-or-throw';const {@@ -10,12 +12,14 @@ const {enqueueJobsMock,listTeamsCalendarPageMock,importTeamsTranscriptHistoryPageMock,+ countTeamsTranscriptHistoryPageMock,listConnectionsMock,} = vi.hoisted(() => ({kvStore: new Map<string, unknown>(),enqueueJobsMock: vi.fn(),listTeamsCalendarPageMock: vi.fn(),importTeamsTranscriptHistoryPageMock: vi.fn(),+ countTeamsTranscriptHistoryPageMock: vi.fn(),listConnectionsMock: vi.fn(),}));@@ -50,7 +54,18 @@ vi.mock(vi.mock('src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts',- () => ({ listTeamsOccurrenceTranscripts: vi.fn().mockResolvedValue([]) }),+ () => ({+ listTeamsOccurrenceTranscripts: vi+ .fn()+ .mockResolvedValue({ transcripts: [], unavailableMeetingCount: 1 }),+ }),+);++vi.mock(+ 'src/features/transcripts/logic-functions/utils/count-teams-transcript-history-page-or-throw',+ () => ({+ countTeamsTranscriptHistoryPageOrThrow: countTeamsTranscriptHistoryPageMock,+ }),);vi.mock(@@ -69,6 +84,7 @@ const NEXT_PAGE_URL =const JOB = {connectedAccountId: 'connected-account-1',runId: 'run-1',+ chunkIndex: 0,pageIndex: 2,attempt: 0,};@@ -77,13 +93,35 @@ const NEXT_JOB = { ...JOB, pageIndex: 3, nextPageUrl: NEXT_PAGE_URL };const STATE = {runId: 'run-1',+ days: 31,windowStart: '2026-08-15T00:00:00.000Z',windowEnd: '2026-09-15T00:00:00.000Z',phase: 'importing',+ transcriptCount: 0,+ alreadyImportedCount: 0,+ deletedCount: 0,pageCount: 2,+ importedCount: 4,+ skippedCount: 1,+ unavailableCount: 0,updatedAt: '2026-09-15T00:10:00.000Z',};+const PAGE_COUNTS = {+ transcriptCount: 0,+ alreadyImportedCount: 0,+ deletedCount: 0,+ importedCount: 0,+ skippedCount: 0,+ unavailableCount: 0,+};++const processImportPage = (+ payload: Parameters<+ typeof processTeamsTranscriptHistoryPageOrThrow+ >[0]['payload'],+) => processTeamsTranscriptHistoryPageOrThrow({ phase: 'importing', payload });+const buildGraphRequestError = (status: number, innerErrorCode?: string) =>new GraphRequestError({message: `Microsoft Graph request failed (${status})`,@@ -108,7 +146,12 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {occurrences: [],nextPageUrl: NEXT_PAGE_URL,});- importTeamsTranscriptHistoryPageMock.mockResolvedValue(2);+ importTeamsTranscriptHistoryPageMock.mockResolvedValue({+ ...PAGE_COUNTS,+ importedCount: 2,+ skippedCount: 1,+ unavailableCount: 1,+ });});it('should save the page before scheduling the next one a minute later', async () => {@@ -119,30 +162,62 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {stateWhenScheduled = kvStore.get(STATE_KV_KEY);});- await processTeamsTranscriptHistoryPageOrThrow(JOB);+ await processImportPage(JOB);expect(stateWhenScheduled).toMatchObject({phase: 'importing',pageCount: 3,+ importedCount: 6,+ skippedCount: 2,+ unavailableCount: 2,nextJob: NEXT_JOB,});+ expect(importTeamsTranscriptHistoryPageMock).toHaveBeenCalledWith(+ expect.objectContaining({ importedSince: STATE.windowEnd }),+ );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);+ importTeamsTranscriptHistoryPageMock.mockResolvedValue(PAGE_COUNTS);- await processTeamsTranscriptHistoryPageOrThrow(JOB);+ await processImportPage(JOB);expect(getEnqueuedJobs()).toEqual([{ payload: NEXT_JOB, delayMs: 0 }]);});+ it('should leave a meeting that started before the chunk to the chunk that holds its start', async () => {+ const meetingInChunk = {+ joinWebUrl: 'in-chunk',+ startDateTime: '2026-09-01T10:00:00.000Z',+ endDateTime: '2026-09-01T10:30:00.000Z',+ calendarReference: { eventExternalId: 'event-in-chunk' },+ };+ const meetingBeforeChunk = {+ ...meetingInChunk,+ joinWebUrl: 'before-chunk',+ startDateTime: '2026-08-14T23:45:00.000Z',+ endDateTime: '2026-08-15T00:15:00.000Z',+ };++ kvStore.set(STATE_KV_KEY, STATE);+ listTeamsCalendarPageMock.mockResolvedValue({+ occurrences: [meetingBeforeChunk, meetingInChunk],+ });++ await processImportPage(JOB);++ expect(listTeamsOccurrenceTranscripts).toHaveBeenCalledWith(+ expect.objectContaining({ occurrences: [meetingInChunk] }),+ );+ });+it('should finish the run on the last calendar page', async () => {kvStore.set(STATE_KV_KEY, STATE);listTeamsCalendarPageMock.mockResolvedValue({ occurrences: [] });- await processTeamsTranscriptHistoryPageOrThrow(JOB);+ await processImportPage(JOB);expect(kvStore.get(STATE_KV_KEY)).toMatchObject({phase: 'imported',@@ -151,6 +226,52 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {expect(enqueueJobsMock).not.toHaveBeenCalled();});+ it('should count the last page of a count without importing it', async () => {+ kvStore.set(STATE_KV_KEY, {+ ...STATE,+ phase: 'counting',+ importedCount: 0,+ });+ listTeamsCalendarPageMock.mockResolvedValue({ occurrences: [] });+ countTeamsTranscriptHistoryPageMock.mockResolvedValue({+ ...PAGE_COUNTS,+ transcriptCount: 5,+ alreadyImportedCount: 2,+ deletedCount: 1,+ });++ await processTeamsTranscriptHistoryPageOrThrow({+ phase: 'counting',+ payload: JOB,+ });++ expect(importTeamsTranscriptHistoryPageMock).not.toHaveBeenCalled();+ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({+ phase: 'counted',+ transcriptCount: 5,+ alreadyImportedCount: 2,+ deletedCount: 1,+ unavailableCount: 1,+ });+ });++ it('should schedule the next page of a count on the count function', async () => {+ kvStore.set(STATE_KV_KEY, { ...STATE, phase: 'counting' });+ countTeamsTranscriptHistoryPageMock.mockResolvedValue(PAGE_COUNTS);++ await processTeamsTranscriptHistoryPageOrThrow({+ phase: 'counting',+ payload: JOB,+ });++ expect(enqueueJobsMock).toHaveBeenCalledWith(+ expect.objectContaining({+ logicFunctionUniversalIdentifier:+ TEAMS_COUNT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER,+ }),+ );+ });+it('should stop a page whose run is removed while it imports', async () => {let wasRunActive: boolean | undefined;@@ -160,13 +281,13 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {kvStore.delete(STATE_KV_KEY);wasRunActive = await isRunActive();- return 0;+ return PAGE_COUNTS;},);- await expect(- processTeamsTranscriptHistoryPageOrThrow(JOB),- ).resolves.toEqual(expect.objectContaining({ skipped: true }));+ await expect(processImportPage(JOB)).resolves.toEqual(+ expect.objectContaining({ skipped: true }),+ );expect(wasRunActive).toBe(false);expect(kvStore.has(STATE_KV_KEY)).toBe(false);expect(enqueueJobsMock).not.toHaveBeenCalled();@@ -176,9 +297,9 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {kvStore.set(STATE_KV_KEY, STATE);listConnectionsMock.mockResolvedValue([]);- await expect(- processTeamsTranscriptHistoryPageOrThrow(JOB),- ).resolves.toEqual(expect.objectContaining({ skipped: true }));+ await expect(processImportPage(JOB)).resolves.toEqual(+ expect.objectContaining({ skipped: true }),+ );expect(kvStore.has(STATE_KV_KEY)).toBe(false);expect(enqueueJobsMock).not.toHaveBeenCalled();});@@ -186,9 +307,9 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {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 }));+ await expect(processImportPage(JOB)).resolves.toEqual(+ expect.objectContaining({ skipped: true }),+ );expect(listTeamsCalendarPageMock).not.toHaveBeenCalled();expect(getEnqueuedJobs()).toEqual([{ payload: NEXT_JOB, delayMs: 0 }]);});@@ -200,9 +321,9 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {])('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 }));+ await expect(processImportPage(JOB)).resolves.toEqual(+ expect.objectContaining({ skipped: true }),+ );expect(kvStore.get(STATE_KV_KEY)).toBe(state);expect(listTeamsCalendarPageMock).not.toHaveBeenCalled();expect(enqueueJobsMock).not.toHaveBeenCalled();@@ -212,7 +333,7 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {kvStore.set(STATE_KV_KEY, STATE);listTeamsCalendarPageMock.mockRejectedValue(buildGraphRequestError(503));- await processTeamsTranscriptHistoryPageOrThrow(JOB);+ await processImportPage(JOB);expect(kvStore.get(STATE_KV_KEY)).toMatchObject({phase: 'importing',@@ -227,25 +348,36 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {});it.each([- ['its last retry failed', 3, buildGraphRequestError(503)],+ ['its last retry failed', 3, buildGraphRequestError(503), 'unknown'],['an admin disabled transcripts',0,buildGraphRequestError(403, 'GraphAccessToTranscriptsDisabled'),+ 'transcripts-disabled-by-admin',],['its connection needs reconnecting',0,new AppConnectionAuthFailedError('connected-account-1'),+ 'reconnect-required',],- ])('should fail the run when %s', async (_, attempt, error) => {+ [+ 'its token was still rejected on the last retry',+ 3,+ buildGraphRequestError(401),+ 'reconnect-required',+ ],+ ])('should fail the run when %s', async (_, attempt, error, errorCode) => {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' });+ await expect(processImportPage({ ...JOB, attempt })).resolves.toEqual(+ expect.objectContaining({ success: false }),+ );+ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({+ phase: 'failed',+ errorCode,+ });expect(enqueueJobsMock).not.toHaveBeenCalled();});@@ -253,7 +385,7 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {kvStore.set(STATE_KV_KEY, STATE);listTeamsCalendarPageMock.mockRejectedValue(buildGraphRequestError(401));- await processTeamsTranscriptHistoryPageOrThrow({ ...JOB, attempt: 1 });+ await processImportPage({ ...JOB, attempt: 1 });expect(kvStore.get(STATE_KV_KEY)).toMatchObject({ phase: 'importing' });expect(getEnqueuedJobs()).toEqual([@@ -264,9 +396,9 @@ describe('processTeamsTranscriptHistoryPageOrThrow', () => {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 }));+ await expect(processImportPage({ ...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.tsindex 9ae6a8fd4a6..795e0f2ef96 100644--- 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.ts@@ -32,6 +32,8 @@ const CONNECTED_ACCOUNT_ID = 'connected-account-1';const STATE_KV_KEY = `teams-transcript-history:${CONNECTED_ACCOUNT_ID}`;+const INITIAL_IMPORT_KV_KEY = `teams-transcript-history-initial-import:${CONNECTED_ACCOUNT_ID}`;+const NOW = Date.parse('2026-09-15T00:00:00.000Z');const EXISTING_STATE = {@@ -67,6 +69,7 @@ describe('startTeamsTranscriptHistoryInitialImportOrThrow', () => {const state = kvStore.get(STATE_KV_KEY) as typeof EXISTING_STATE;+ expect(kvStore.get(INITIAL_IMPORT_KV_KEY)).toBe(true);expect(state).toMatchObject({windowStart: '2026-08-15T00:00:00.000Z',windowEnd: '2026-09-15T00:00:00.000Z',@@ -80,6 +83,7 @@ describe('startTeamsTranscriptHistoryInitialImportOrThrow', () => {payload: {connectedAccountId: CONNECTED_ACCOUNT_ID,runId: state.runId,+ chunkIndex: 0,pageIndex: 0,attempt: 0,},@@ -92,7 +96,12 @@ describe('startTeamsTranscriptHistoryInitialImportOrThrow', () => {it.each([['is running', EXISTING_STATE],['finished', { ...EXISTING_STATE, phase: 'imported' }],+ [+ 'reached the page limit',+ { ...EXISTING_STATE, phase: 'failed', errorCode: 'page-limit-reached' },+ ],])('should keep an import that %s', async (_, existingState) => {+ kvStore.set(INITIAL_IMPORT_KV_KEY, true);kvStore.set(STATE_KV_KEY, existingState);await startInitialImport();@@ -111,6 +120,7 @@ describe('startTeamsTranscriptHistoryInitialImportOrThrow', () => {},],])('should restart an import that %s', async (_, existingState) => {+ kvStore.set(INITIAL_IMPORT_KV_KEY, true);kvStore.set(STATE_KV_KEY, existingState);await startInitialImport();@@ -123,6 +133,18 @@ describe('startTeamsTranscriptHistoryInitialImportOrThrow', () => {expect(enqueueJobsMock).toHaveBeenCalledTimes(1);});+ it('should import the last 31 days even when a count already ran on the connection', async () => {+ kvStore.set(STATE_KV_KEY, { ...EXISTING_STATE, phase: 'counted' });++ await startInitialImport();++ expect(kvStore.get(STATE_KV_KEY)).toMatchObject({+ phase: 'importing',+ pageCount: 0,+ });+ expect(enqueueJobsMock).toHaveBeenCalledTimes(1);+ });+it('should mark the import failed when its first page cannot be scheduled', async () => {enqueueJobsMock.mockRejectedValue(new Error('queue unavailable'));@@ -135,7 +157,7 @@ describe('startTeamsTranscriptHistoryInitialImportOrThrow', () => {await startInitialImport();- expect(kvStore.has(STATE_KV_KEY)).toBe(false);+ expect(kvStore.size).toBe(0);});it('should not import anything while transcripts are off', async () => {diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-history-initial-import-kv-key.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-history-initial-import-kv-key.tsnew file mode 100644index 00000000000..0061f47888c--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-transcript-history-initial-import-kv-key.ts@@ -0,0 +1,6 @@+import { TEAMS_TRANSCRIPT_HISTORY_INITIAL_IMPORT_KV_KEY_PREFIX } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-initial-import-kv-key-prefix';++export const buildTeamsTranscriptHistoryInitialImportKvKey = (+ connectedAccountId: string,+): string =>+ `${TEAMS_TRANSCRIPT_HISTORY_INITIAL_IMPORT_KV_KEY_PREFIX}:${connectedAccountId}`;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/count-teams-transcript-history-page-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/count-teams-transcript-history-page-or-throw.tsnew file mode 100644index 00000000000..f5b3defbbfd--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/count-teams-transcript-history-page-or-throw.ts@@ -0,0 +1,31 @@+import { type CoreApiClient } from 'twenty-client-sdk/core';++import { type TeamsOccurrenceTranscript } from 'src/features/transcripts/logic-functions/types/teams-occurrence-transcript.type';+import { type TeamsTranscriptHistoryPageCounts } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-page-counts.type';+import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';+import { findDeletedAndCompletedCallRecordingIdsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-deleted-and-completed-call-recording-ids-or-throw';++export const countTeamsTranscriptHistoryPageOrThrow = async ({+ coreApiClient,+ transcripts,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ transcripts: TeamsOccurrenceTranscript[];+}): Promise<TeamsTranscriptHistoryPageCounts> => {+ const { deletedCallRecordingIds, completedCallRecordingIds } =+ await findDeletedAndCompletedCallRecordingIdsOrThrow({+ coreApiClient,+ callRecordingIds: transcripts.map(({ transcript }) =>+ computeCallRecordingIdForTeamsTranscript(transcript.id),+ ),+ });++ return {+ transcriptCount: transcripts.length,+ alreadyImportedCount: completedCallRecordingIds.size,+ deletedCount: deletedCallRecordingIds.size,+ importedCount: 0,+ skippedCount: 0,+ unavailableCount: 0,+ };+};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.tsindex d7e60124493..13e89914909 100644--- 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.ts@@ -1,5 +1,6 @@import { kv } from 'twenty-sdk/logic-function';+import { buildTeamsTranscriptHistoryInitialImportKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-history-initial-import-kv-key';import { buildTeamsTranscriptHistoryKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-history-kv-key';export const deleteTeamsTranscriptHistoryKvKeys = async ({@@ -7,5 +8,10 @@ export const deleteTeamsTranscriptHistoryKvKeys = async ({}: {connectedAccountId: string;}): Promise<void> => {- await kv.delete(buildTeamsTranscriptHistoryKvKey(connectedAccountId));+ await Promise.all([+ kv.delete(buildTeamsTranscriptHistoryKvKey(connectedAccountId)),+ kv.delete(+ buildTeamsTranscriptHistoryInitialImportKvKey(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.tsindex f67ee6b10a8..9ac5c5ebfd0 100644--- 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.ts@@ -3,25 +3,33 @@ import {RetryableLogicFunctionError,} from 'twenty-sdk/logic-function';-import { TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER } from 'src/features/transcripts/constants/universal-identifiers';+import {+ TEAMS_COUNT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER,+ 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 { type TeamsTranscriptHistoryRunningPhase } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.type';import { toErrorMessage } from 'src/utils/to-error-message';export const enqueueTeamsTranscriptHistoryJobOrThrow = async ({+ phase,job,delayMilliseconds,}: {+ phase: TeamsTranscriptHistoryRunningPhase;job: TeamsTranscriptHistoryJobPayload;delayMilliseconds: number;}): Promise<void> => {try {await enqueueJobs({logicFunctionUniversalIdentifier:- TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER,+ phase === 'counting'+ ? TEAMS_COUNT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER+ : TEAMS_IMPORT_TRANSCRIPT_HISTORY_UNIVERSAL_IDENTIFIER,jobs: [{- jobId: `teams-transcript-history-importing-${job.runId}-${job.pageIndex}-${job.attempt}`,+ jobId: `teams-transcript-history-${phase}-${job.runId}-${job.chunkIndex}-${job.pageIndex}-${job.attempt}`,payload: job,},],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.tsindex 67387ad07b2..d5d9d3b9b46 100644--- 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.ts@@ -4,23 +4,31 @@ import { isDefined } from 'twenty-sdk/utils';type ExistingCallRecording = {id: string;status: string | null;+ createdAt: string;deletedAt: string | null;};+const getCallRecordingIds = (callRecordings: ExistingCallRecording[]) =>+ new Set(callRecordings.map((callRecording) => callRecording.id));+export const findDeletedAndCompletedCallRecordingIdsOrThrow = async ({coreApiClient,callRecordingIds,+ importedSince,}: {coreApiClient: Pick<CoreApiClient, 'query'>;callRecordingIds: string[];+ importedSince?: string;}): Promise<{deletedCallRecordingIds: Set<string>;completedCallRecordingIds: Set<string>;+ importedCallRecordingIds: Set<string>;}> => {if (callRecordingIds.length === 0) {return {deletedCallRecordingIds: new Set(),completedCallRecordingIds: new Set(),+ importedCallRecordingIds: new Set(),};}@@ -38,26 +46,36 @@ export const findDeletedAndCompletedCallRecordingIdsOrThrow = async ({},first: callRecordingIds.length,},- edges: { node: { id: true, status: true, deletedAt: true } },+ edges: {+ node: { id: true, status: true, createdAt: true, deletedAt: true },+ },},});const callRecordings =result.callRecordings?.edges?.map((edge) => edge.node) ?? [];+ const completedCallRecordings = callRecordings.filter(+ (callRecording) =>+ !isDefined(callRecording.deletedAt) &&+ callRecording.status === 'COMPLETED',+ );+ // A recording this run created was written by a failed attempt of the page.+ const isImportedByThisRun = (callRecording: ExistingCallRecording) =>+ isDefined(importedSince) &&+ Date.parse(callRecording.createdAt) >= Date.parse(importedSince);return {- deletedCallRecordingIds: new Set(- callRecordings- .filter((callRecording) => isDefined(callRecording.deletedAt))- .map((callRecording) => callRecording.id),+ deletedCallRecordingIds: getCallRecordingIds(+ callRecordings.filter((callRecording) =>+ isDefined(callRecording.deletedAt),+ ),+ ),+ completedCallRecordingIds: getCallRecordingIds(+ completedCallRecordings.filter(+ (callRecording) => !isImportedByThisRun(callRecording),+ ),),- completedCallRecordingIds: new Set(- callRecordings- .filter(- (callRecording) =>- !isDefined(callRecording.deletedAt) &&- callRecording.status === 'COMPLETED',- )- .map((callRecording) => callRecording.id),+ importedCallRecordingIds: getCallRecordingIds(+ completedCallRecordings.filter(isImportedByThisRun),),};};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw.tsindex 58b8b8f8f29..666fa50a887 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw.ts@@ -6,23 +6,41 @@ import {import { isDefined } from 'twenty-sdk/utils';import { TEAMS_PROVIDER_NAME } from 'src/features/transcripts/constants/teams-provider-name';+import { TeamsConnectionUnavailableError } from 'src/features/transcripts/logic-functions/types/teams-connection-unavailable-error';export const getTeamsConnectionForRequestOrThrow = async (context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>,+ {+ isOwnConnectionRequired = false,+ }: { isOwnConnectionRequired?: boolean } = {},) => {+ const connections = await listConnections({+ providerName: TEAMS_PROVIDER_NAME,+ });const connection = findConnectionForRequest(- await listConnections({ providerName: TEAMS_PROVIDER_NAME }),+ isOwnConnectionRequired+ ? connections.filter(+ (connection) =>+ isDefined(context.userWorkspaceId) &&+ connection.userWorkspaceId === context.userWorkspaceId,+ )+ : connections,context,);if (!isDefined(connection)) {- throw new Error(- 'Microsoft Teams is not connected. Open Microsoft Teams app settings and add a connection first.',- );+ throw new TeamsConnectionUnavailableError({+ message:+ 'Microsoft Teams is not connected. Open Microsoft Teams app settings and add a connection first.',+ code: 'not-connected',+ });}if (isDefined(connection.authFailedAt)) {- throw new Error('Reconnect Microsoft Teams in the app settings.');+ throw new TeamsConnectionUnavailableError({+ message: 'Reconnect Microsoft Teams in the app settings.',+ code: 'reconnect-required',+ });}return connection;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-transcript-history-chunk-window.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-transcript-history-chunk-window.tsnew file mode 100644index 00000000000..27c6458a647--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-transcript-history-chunk-window.ts@@ -0,0 +1,33 @@+import { MILLISECONDS_PER_DAY } from 'src/features/transcripts/logic-functions/constants/milliseconds-per-day';+import { TEAMS_TRANSCRIPT_HISTORY_CHUNK_DAYS } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-chunk-days';+import { type TeamsMeetingWindow } from 'src/features/transcripts/logic-functions/types/teams-meeting-window.type';++export const getTeamsTranscriptHistoryChunkWindow = ({+ windowStart,+ windowEnd,+ chunkIndex,+}: {+ windowStart: string;+ windowEnd: string;+ chunkIndex: number;+}): TeamsMeetingWindow | undefined => {+ const chunkMilliseconds =+ TEAMS_TRANSCRIPT_HISTORY_CHUNK_DAYS * MILLISECONDS_PER_DAY;+ const windowStartMilliseconds = Date.parse(windowStart);+ const chunkEndMilliseconds =+ Date.parse(windowEnd) - chunkIndex * chunkMilliseconds;++ if (chunkEndMilliseconds <= windowStartMilliseconds) {+ return undefined;+ }++ return {+ startDateTime: new Date(+ Math.max(+ windowStartMilliseconds,+ chunkEndMilliseconds - chunkMilliseconds,+ ),+ ).toISOString(),+ endDateTime: new Date(chunkEndMilliseconds).toISOString(),+ };+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-transcript-history-page-transition.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-transcript-history-page-transition.tsnew file mode 100644index 00000000000..955757254c5--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-transcript-history-page-transition.ts@@ -0,0 +1,110 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isDefined } from 'twenty-sdk/utils';++import { TEAMS_TRANSCRIPT_HISTORY_MAX_PAGES } from 'src/features/transcripts/logic-functions/constants/teams-transcript-history-max-pages';+import { type TeamsTranscriptHistoryJobPayload } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-job-payload.type';+import { type TeamsTranscriptHistoryPageCounts } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-page-counts.type';+import { type TeamsTranscriptHistoryRunningPhase } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.type';+import { type TeamsTranscriptHistoryState } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-state.type';+import { getTeamsTranscriptHistoryChunkWindow } from 'src/features/transcripts/logic-functions/utils/get-teams-transcript-history-chunk-window';++const getNextJob = ({+ state,+ job,+ nextPageUrl,+}: {+ state: TeamsTranscriptHistoryState;+ job: TeamsTranscriptHistoryJobPayload;+ nextPageUrl?: string;+}): TeamsTranscriptHistoryJobPayload | undefined => {+ if (isNonEmptyString(nextPageUrl)) {+ return {+ ...job,+ pageIndex: job.pageIndex + 1,+ attempt: 0,+ nextPageUrl,+ };+ }++ const nextChunkIndex = job.chunkIndex + 1;++ return isDefined(+ getTeamsTranscriptHistoryChunkWindow({+ windowStart: state.windowStart,+ windowEnd: state.windowEnd,+ chunkIndex: nextChunkIndex,+ }),+ )+ ? {+ connectedAccountId: job.connectedAccountId,+ runId: job.runId,+ chunkIndex: nextChunkIndex,+ pageIndex: job.pageIndex + 1,+ attempt: 0,+ }+ : undefined;+};++const getPhaseAfterPage = ({+ phase,+ nextJob,+}: {+ phase: TeamsTranscriptHistoryRunningPhase;+ nextJob: TeamsTranscriptHistoryJobPayload | undefined;+}): Pick<TeamsTranscriptHistoryState, 'phase' | 'errorCode'> => {+ if (!isDefined(nextJob)) {+ return { phase: phase === 'counting' ? 'counted' : 'imported' };+ }++ if (nextJob.pageIndex >= TEAMS_TRANSCRIPT_HISTORY_MAX_PAGES) {+ return { phase: 'failed', errorCode: 'page-limit-reached' };+ }++ return { phase };+};++export const getTeamsTranscriptHistoryPageTransition = ({+ state,+ job,+ phase,+ pageCounts,+ nextPageUrl,+ now,+}: {+ state: TeamsTranscriptHistoryState;+ job: TeamsTranscriptHistoryJobPayload;+ phase: TeamsTranscriptHistoryRunningPhase;+ pageCounts: TeamsTranscriptHistoryPageCounts;+ nextPageUrl?: string;+ now: number;+}): {+ state: TeamsTranscriptHistoryState;+ nextJob?: TeamsTranscriptHistoryJobPayload;+} => {+ const nextJob = getNextJob({ state, job, nextPageUrl });+ const phaseAfterPage = getPhaseAfterPage({ phase, nextJob });++ return {+ state: {+ ...state,+ ...phaseAfterPage,+ transcriptCount: state.transcriptCount + pageCounts.transcriptCount,+ alreadyImportedCount:+ state.alreadyImportedCount + pageCounts.alreadyImportedCount,+ deletedCount: state.deletedCount + pageCounts.deletedCount,+ importedCount: state.importedCount + pageCounts.importedCount,+ skippedCount: state.skippedCount + pageCounts.skippedCount,+ unavailableCount: state.unavailableCount + pageCounts.unavailableCount,+ pageCount: job.pageIndex + 1,+ checkedThrough: isNonEmptyString(nextPageUrl)+ ? state.checkedThrough+ : getTeamsTranscriptHistoryChunkWindow({+ windowStart: state.windowStart,+ windowEnd: state.windowEnd,+ chunkIndex: job.chunkIndex,+ })?.startDateTime,+ updatedAt: new Date(now).toISOString(),+ },+ ...(phaseAfterPage.phase === phase ? { nextJob } : {}),+ };+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/handle-teams-transcript-history-route.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/handle-teams-transcript-history-route.tsnew file mode 100644index 00000000000..6be4149cfc8--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/handle-teams-transcript-history-route.ts@@ -0,0 +1,47 @@+import { type LogicFunctionExecutionContext } from 'twenty-sdk/logic-function';++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 { TeamsConnectionUnavailableError } from 'src/features/transcripts/logic-functions/types/teams-connection-unavailable-error';+import { type TeamsTranscriptHistoryRouteResult } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type';+import { getTeamsConnectionForRequestOrThrow } from 'src/features/transcripts/logic-functions/utils/get-teams-connection-for-request-or-throw';+import { toErrorMessage } from 'src/utils/to-error-message';+import { isFeatureEnabled } from 'src/utils/is-feature-enabled';++export const handleTeamsTranscriptHistoryRoute = async ({+ context,+ failureLogMessage,+ handle,+}: {+ context: Pick<LogicFunctionExecutionContext, 'userWorkspaceId'>;+ failureLogMessage: string;+ handle: (+ connectedAccountId: string,+ ) => Promise<TeamsTranscriptHistoryRouteResult>;+}): Promise<TeamsTranscriptHistoryRouteResult> => {+ if (+ !isFeatureEnabled({+ isAvailable: FEATURE_FLAGS.IS_TRANSCRIPT_IMPORT_ENABLED,+ settingValue: process.env[TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY],+ })+ ) {+ return { success: false, errorCode: 'transcripts-not-enabled' };+ }++ try {+ // A history import pulls in every meeting of an account, so only the member who added the connection may run it.+ const connection = await getTeamsConnectionForRequestOrThrow(context, {+ isOwnConnectionRequired: true,+ });++ return await handle(connection.id);+ } catch (error) {+ if (error instanceof TeamsConnectionUnavailableError) {+ return { success: false, errorCode: error.code };+ }++ console.error(`[teams] ${failureLogMessage}: ${toErrorMessage(error)}`);++ return { success: false, errorCode: 'unknown' };+ }+};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.tsindex 170d7f943e7..f862569ecfc 100644--- 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.ts@@ -4,6 +4,7 @@ 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 { type TeamsTranscriptHistoryPageCounts } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-page-counts.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';@@ -42,13 +43,15 @@ export const importTeamsTranscriptHistoryPageOrThrow = async ({accessToken,coreApiClient,transcripts,+ importedSince,isRunActive,}: {accessToken: string;coreApiClient: Pick<CoreApiClient, 'query' | 'mutation'>;transcripts: TeamsOccurrenceTranscript[];+ importedSince: string;isRunActive: () => Promise<boolean>;-}): Promise<number> => {+}): Promise<TeamsTranscriptHistoryPageCounts> => {const pageTranscripts = [...new Map(transcripts.map((occurrenceTranscript) => {@@ -60,17 +63,22 @@ export const importTeamsTranscriptHistoryPageOrThrow = async ({}),).values(),];- const { deletedCallRecordingIds, completedCallRecordingIds } =- await findDeletedAndCompletedCallRecordingIdsOrThrow({- coreApiClient,- callRecordingIds: pageTranscripts.map(- ({ callRecordingId }) => callRecordingId,- ),- });+ const {+ deletedCallRecordingIds,+ completedCallRecordingIds,+ importedCallRecordingIds,+ } = await findDeletedAndCompletedCallRecordingIdsOrThrow({+ coreApiClient,+ callRecordingIds: pageTranscripts.map(+ ({ callRecordingId }) => callRecordingId,+ ),+ importedSince,+ });const importableTranscripts = pageTranscripts.filter(({ callRecordingId }) =>!deletedCallRecordingIds.has(callRecordingId) &&- !completedCallRecordingIds.has(callRecordingId),+ !completedCallRecordingIds.has(callRecordingId) &&+ !importedCallRecordingIds.has(callRecordingId),);const calendarEventIds = await findTeamsCalendarEventIdsOrThrow({accessToken,@@ -79,7 +87,10 @@ export const importTeamsTranscriptHistoryPageOrThrow = async ({.map(({ calendarReference }) => calendarReference).filter(isDefined),});- let importedCount = 0;+ let importedCount = importedCallRecordingIds.size;+ let skippedCount =+ deletedCallRecordingIds.size + completedCallRecordingIds.size;+ let unavailableCount = 0;for (const transcriptBatch of chunkIntoBatches(importableTranscripts,@@ -107,6 +118,7 @@ export const importTeamsTranscriptHistoryPageOrThrow = async ({: [];if (!isNonEmptyArray(transcriptEntries)) {+ unavailableCount += 1;continue;}@@ -137,6 +149,8 @@ export const importTeamsTranscriptHistoryPageOrThrow = async ({!callRecordingIdsBeforeWrite.completedCallRecordingIds.has(id),);+ skippedCount += callRecordings.length - upsertableCallRecordings.length;+if (upsertableCallRecordings.length === 0) {continue;}@@ -154,5 +168,12 @@ export const importTeamsTranscriptHistoryPageOrThrow = async ({importedCount += upsertableCallRecordings.length;}- return importedCount;+ return {+ transcriptCount: 0,+ alreadyImportedCount: 0,+ deletedCount: 0,+ importedCount,+ skippedCount,+ unavailableCount,+ };};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-meeting-occurrence-starting-in-window.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-meeting-occurrence-starting-in-window.tsnew file mode 100644index 00000000000..9fdf701f114--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/is-teams-meeting-occurrence-starting-in-window.ts@@ -0,0 +1,17 @@+import { type TeamsMeetingOccurrence } from 'src/features/transcripts/logic-functions/types/teams-meeting-occurrence.type';+import { type TeamsMeetingWindow } from 'src/features/transcripts/logic-functions/types/teams-meeting-window.type';++export const isTeamsMeetingOccurrenceStartingInWindow = ({+ occurrence,+ window,+}: {+ occurrence: Pick<TeamsMeetingOccurrence, 'startDateTime'>;+ window: TeamsMeetingWindow;+}): boolean => {+ const startMilliseconds = Date.parse(occurrence.startDateTime);++ return (+ startMilliseconds >= Date.parse(window.startDateTime) &&+ startMilliseconds < Date.parse(window.endDateTime)+ );+};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.tsindex 515bb601054..045c8199a25 100644--- 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.ts@@ -8,6 +8,6 @@ export const isTeamsTranscriptHistoryStalled = ({state: Pick<TeamsTranscriptHistoryState, 'phase' | 'updatedAt'>;now: number;}): boolean =>- state.phase === 'importing' &&+ (state.phase === 'counting' || 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/list-teams-occurrence-transcripts.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/list-teams-occurrence-transcripts.tsindex 61b23270063..04cae7f4f52 100644--- 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.ts@@ -16,7 +16,7 @@ const listAvailableMeetingTranscriptsOrThrow = async ({}: {accessToken: string;meetingId: string;-}): Promise<GraphCallTranscript[]> => {+}): Promise<GraphCallTranscript[] | undefined> => {try {return await listMeetingTranscripts({ accessToken, meetingId });} catch (error) {@@ -28,7 +28,7 @@ const listAvailableMeetingTranscriptsOrThrow = async ({`[teams] skipped a meeting whose transcripts Microsoft Graph could not list: ${toErrorMessage(error)}`,);- return [];+ return undefined;}};@@ -40,7 +40,7 @@ const listMeetingOccurrenceTranscriptsOrThrow = async ({accessToken: string;joinWebUrl: string;occurrences: TeamsMeetingOccurrence[];-}): Promise<TeamsOccurrenceTranscript[]> => {+}): Promise<TeamsOccurrenceTranscript[] | undefined> => {const meeting = await getMeetingByJoinUrl({ accessToken, joinWebUrl });if (!isDefined(meeting)) {@@ -53,7 +53,7 @@ const listMeetingOccurrenceTranscriptsOrThrow = async ({});return meetingTranscripts- .filter((transcript) =>+ ?.filter((transcript) =>occurrences.some((occurrence) =>isTranscriptDuringOccurrence({ transcript, occurrence }),),@@ -74,23 +74,31 @@ export const listTeamsOccurrenceTranscripts = async ({}: {accessToken: string;occurrences: TeamsMeetingOccurrence[];-}): Promise<TeamsOccurrenceTranscript[]> => {+}): Promise<{+ transcripts: TeamsOccurrenceTranscript[];+ unavailableMeetingCount: number;+}> => {const joinWebUrls = [...new Set(occurrences.map((occurrence) => occurrence.joinWebUrl)),];const transcripts: TeamsOccurrenceTranscript[] = [];+ let unavailableMeetingCount = 0;for (const joinWebUrl of joinWebUrls) {- transcripts.push(- ...(await listMeetingOccurrenceTranscriptsOrThrow({- accessToken,- joinWebUrl,- occurrences: occurrences.filter(- (occurrence) => occurrence.joinWebUrl === joinWebUrl,- ),- })),- );+ const meetingTranscripts = await listMeetingOccurrenceTranscriptsOrThrow({+ accessToken,+ joinWebUrl,+ occurrences: occurrences.filter(+ (occurrence) => occurrence.joinWebUrl === joinWebUrl,+ ),+ });++ if (isDefined(meetingTranscripts)) {+ transcripts.push(...meetingTranscripts);+ } else {+ unavailableMeetingCount += 1;+ }}- return transcripts;+ return { transcripts, unavailableMeetingCount };};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.tsindex c7e5e5476f5..7c4c705c557 100644--- 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.ts@@ -14,29 +14,43 @@ import { TRANSCRIPTS_ENABLED_APPLICATION_VARIABLE_KEY } from 'src/features/transimport { 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 TeamsTranscriptHistoryErrorCode } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-error-code.type';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 TeamsTranscriptHistoryRunningPhase } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.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 { countTeamsTranscriptHistoryPageOrThrow } from 'src/features/transcripts/logic-functions/utils/count-teams-transcript-history-page-or-throw';import { enqueueTeamsTranscriptHistoryJobOrThrow } from 'src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-history-job-or-throw';+import { getTeamsTranscriptHistoryChunkWindow } from 'src/features/transcripts/logic-functions/utils/get-teams-transcript-history-chunk-window';+import { getTeamsTranscriptHistoryPageTransition } from 'src/features/transcripts/logic-functions/utils/get-teams-transcript-history-page-transition';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 { isTeamsMeetingOccurrenceStartingInWindow } from 'src/features/transcripts/logic-functions/utils/is-teams-meeting-occurrence-starting-in-window';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> => {+type TeamsTranscriptHistoryPageJob = {+ job: TeamsTranscriptHistoryJobPayload;+ phase: TeamsTranscriptHistoryRunningPhase;+};++const findStateForJob = async ({+ job,+ phase,+}: TeamsTranscriptHistoryPageJob): Promise<+ TeamsTranscriptHistoryState | undefined+> => {const state = await kv.get<TeamsTranscriptHistoryState>(buildTeamsTranscriptHistoryKvKey(job.connectedAccountId),);- return state?.runId === job.runId && state.phase === 'importing'+ return state?.runId === job.runId && state.phase === phase? state: undefined;};@@ -47,10 +61,24 @@ const isFatalError = (error: unknown): boolean =>error.status === 403 &&error.innerErrorCode === GRAPH_ACCESS_TO_TRANSCRIPTS_DISABLED_ERROR_CODE);-const importPageOrThrow = async (- job: TeamsTranscriptHistoryJobPayload,-): Promise<TeamsTranscriptHistoryPageResult> => {- const state = await findStateForJob(job);+const getFailureErrorCode = (+ error: unknown,+): TeamsTranscriptHistoryErrorCode => {+ if (+ error instanceof AppConnectionAuthFailedError ||+ (error instanceof GraphRequestError && error.status === 401)+ ) {+ return 'reconnect-required';+ }++ return isFatalError(error) ? 'transcripts-disabled-by-admin' : 'unknown';+};++const processPageOrThrow = async ({+ job,+ phase,+}: TeamsTranscriptHistoryPageJob): Promise<TeamsTranscriptHistoryPageResult> => {+ const state = await findStateForJob({ job, phase });if (!isDefined(state) ||@@ -67,6 +95,7 @@ const importPageOrThrow = async (if (state.pageCount === job.pageIndex + 1) {if (isDefined(state.nextJob)) {await enqueueTeamsTranscriptHistoryJobOrThrow({+ phase,job: state.nextJob,delayMilliseconds: 0,});@@ -79,26 +108,53 @@ const importPageOrThrow = async (};}+ const chunkWindow = getTeamsTranscriptHistoryChunkWindow({+ windowStart: state.windowStart,+ windowEnd: state.windowEnd,+ chunkIndex: job.chunkIndex,+ });++ if (!isDefined(chunkWindow)) {+ return { success: false, error: 'Invalid Teams transcript history job' };+ }+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,- }),+ : buildTeamsCalendarViewUrl(chunkWindow),});- const importedCount = await importTeamsTranscriptHistoryPageOrThrow({- accessToken,- coreApiClient: new CoreApiClient({ runAs: 'application' }),- transcripts: await listTeamsOccurrenceTranscripts({+ const { transcripts, unavailableMeetingCount } =+ await listTeamsOccurrenceTranscripts({accessToken,- occurrences: page.occurrences,- }),- isRunActive: async () => isDefined(await findStateForJob(job)),- });- const currentState = await findStateForJob(job);+ occurrences: page.occurrences.filter((occurrence) =>+ isTeamsMeetingOccurrenceStartingInWindow({+ occurrence,+ window: chunkWindow,+ }),+ ),+ });+ const coreApiClient = new CoreApiClient({ runAs: 'application' });+ const phaseCounts =+ phase === 'counting'+ ? await countTeamsTranscriptHistoryPageOrThrow({+ coreApiClient,+ transcripts,+ })+ : await importTeamsTranscriptHistoryPageOrThrow({+ accessToken,+ coreApiClient,+ transcripts,+ importedSince: state.windowEnd,+ isRunActive: async () =>+ isDefined(await findStateForJob({ job, phase })),+ });+ const pageCounts = {+ ...phaseCounts,+ unavailableCount: phaseCounts.unavailableCount + unavailableMeetingCount,+ };+ const currentState = await findStateForJob({ job, phase });if (!isDefined(currentState) || currentState.pageCount !== job.pageIndex) {return {@@ -108,24 +164,20 @@ const importPageOrThrow = async (};}- const nextJob = isNonEmptyString(page.nextPageUrl)- ? {- ...job,- pageIndex: job.pageIndex + 1,- attempt: 0,- nextPageUrl: page.nextPageUrl,- }- : undefined;+ const { state: nextState, nextJob } = getTeamsTranscriptHistoryPageTransition(+ {+ state: currentState,+ job,+ phase,+ pageCounts,+ nextPageUrl: page.nextPageUrl,+ now: Date.now(),+ },+ );await kv.set<TeamsTranscriptHistoryState>(buildTeamsTranscriptHistoryKvKey(job.connectedAccountId),- {- ...currentState,- phase: isDefined(nextJob) ? 'importing' : 'imported',- pageCount: job.pageIndex + 1,- updatedAt: new Date().toISOString(),- nextJob,- },+ { ...nextState, nextJob },);// Disconnecting deletes the run state, and kv cannot make this save conditional on it.@@ -143,9 +195,10 @@ const importPageOrThrow = async (if (isDefined(nextJob)) {await enqueueTeamsTranscriptHistoryJobOrThrow({+ phase,job: nextJob,delayMilliseconds:- importedCount > 0+ pageCounts.importedCount > 0? TEAMS_TRANSCRIPT_HISTORY_IMPORT_PAGE_DELAY_MILLISECONDS: 0,});@@ -156,12 +209,12 @@ const importPageOrThrow = async (const retryOrFailPageOrThrow = async ({job,+ phase,error,-}: {- job: TeamsTranscriptHistoryJobPayload;+}: TeamsTranscriptHistoryPageJob & {error: unknown;}): Promise<TeamsTranscriptHistoryPageResult> => {- const state = await findStateForJob(job);+ const state = await findStateForJob({ job, phase });if (!isDefined(state)) {return {@@ -179,6 +232,7 @@ const retryOrFailPageOrThrow = async ({await kv.set<TeamsTranscriptHistoryState>(stateKvKey, {...state,phase: 'failed',+ errorCode: getFailureErrorCode(error),updatedAt: new Date().toISOString(),});@@ -190,6 +244,7 @@ const retryOrFailPageOrThrow = async ({updatedAt: new Date().toISOString(),});await enqueueTeamsTranscriptHistoryJobOrThrow({+ phase,job: { ...job, attempt: job.attempt + 1 },delayMilliseconds: retryDelayMilliseconds,});@@ -197,15 +252,26 @@ const retryOrFailPageOrThrow = async ({return { success: true, retryScheduled: true };};-export const processTeamsTranscriptHistoryPageOrThrow = async (- payload: Partial<Record<keyof TeamsTranscriptHistoryJobPayload, unknown>>,-): Promise<TeamsTranscriptHistoryPageResult> => {- const { connectedAccountId, runId, pageIndex, attempt, nextPageUrl } =- payload;+export const processTeamsTranscriptHistoryPageOrThrow = async ({+ phase,+ payload,+}: {+ phase: TeamsTranscriptHistoryRunningPhase;+ payload: Partial<Record<keyof TeamsTranscriptHistoryJobPayload, unknown>>;+}): Promise<TeamsTranscriptHistoryPageResult> => {+ const {+ connectedAccountId,+ runId,+ chunkIndex,+ pageIndex,+ attempt,+ nextPageUrl,+ } = payload;if (!isNonEmptyString(connectedAccountId) ||!isNonEmptyString(runId) ||+ !isNonNegativeInteger(chunkIndex) ||!isNonNegativeInteger(pageIndex) ||!isNonNegativeInteger(attempt) ||(isDefined(nextPageUrl) && !isNonEmptyString(nextPageUrl))@@ -229,13 +295,14 @@ export const processTeamsTranscriptHistoryPageOrThrow = async (const job: TeamsTranscriptHistoryJobPayload = {connectedAccountId,runId,+ chunkIndex,pageIndex,attempt,...(isNonEmptyString(nextPageUrl) ? { nextPageUrl } : {}),};try {- return await importPageOrThrow(job);+ return await processPageOrThrow({ job, phase });} catch (error) {if (error instanceof RetryableLogicFunctionError) {throw error;@@ -246,7 +313,7 @@ export const processTeamsTranscriptHistoryPageOrThrow = async ();try {- return await retryOrFailPageOrThrow({ job, error });+ return await retryOrFailPageOrThrow({ job, phase, error });} catch (recoveryError) {if (recoveryError instanceof RetryableLogicFunctionError) {throw recoveryError;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/schedule-teams-transcript-history-run-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/schedule-teams-transcript-history-run-or-throw.tsnew file mode 100644index 00000000000..c2098fc2e67--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/schedule-teams-transcript-history-run-or-throw.ts@@ -0,0 +1,43 @@+import { kv } from 'twenty-sdk/logic-function';++import { type TeamsTranscriptHistoryRunningPhase } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.type';+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 { enqueueTeamsTranscriptHistoryJobOrThrow } from 'src/features/transcripts/logic-functions/utils/enqueue-teams-transcript-history-job-or-throw';++export const scheduleTeamsTranscriptHistoryRunOrThrow = async ({+ connectedAccountId,+ state,+ stateOnScheduleFailure,+}: {+ connectedAccountId: string;+ state: TeamsTranscriptHistoryState & {+ phase: TeamsTranscriptHistoryRunningPhase;+ };+ stateOnScheduleFailure: TeamsTranscriptHistoryState;+}): Promise<void> => {+ const stateKvKey = buildTeamsTranscriptHistoryKvKey(connectedAccountId);++ await kv.set(stateKvKey, state);++ try {+ await enqueueTeamsTranscriptHistoryJobOrThrow({+ phase: state.phase,+ job: {+ connectedAccountId,+ runId: state.runId,+ chunkIndex: 0,+ pageIndex: 0,+ attempt: 0,+ },+ delayMilliseconds: 0,+ });+ } catch (error) {+ await kv.set<TeamsTranscriptHistoryState>(+ stateKvKey,+ stateOnScheduleFailure,+ );++ throw error;+ }+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-count-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-count-or-throw.tsnew file mode 100644index 00000000000..43226a1166e--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-count-or-throw.ts@@ -0,0 +1,36 @@+import { kv } from 'twenty-sdk/logic-function';+import { isDefined } from 'twenty-sdk/utils';++import { type TeamsTranscriptHistoryRouteResult } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type';+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 { isTeamsTranscriptHistoryStalled } from 'src/features/transcripts/logic-functions/utils/is-teams-transcript-history-stalled';+import { startTeamsTranscriptHistoryRunOrThrow } from 'src/features/transcripts/logic-functions/utils/start-teams-transcript-history-run-or-throw';++export const startTeamsTranscriptHistoryCountOrThrow = async ({+ connectedAccountId,+ days,+}: {+ connectedAccountId: string;+ days: number;+}): Promise<TeamsTranscriptHistoryRouteResult> => {+ const currentState = await kv.get<TeamsTranscriptHistoryState>(+ buildTeamsTranscriptHistoryKvKey(connectedAccountId),+ );++ if (+ isDefined(currentState) &&+ (currentState.phase === 'counting' || currentState.phase === 'importing') &&+ !isTeamsTranscriptHistoryStalled({ state: currentState, now: Date.now() })+ ) {+ return { success: false, errorCode: 'run-already-active' };+ }++ const state = await startTeamsTranscriptHistoryRunOrThrow({+ connectedAccountId,+ days,+ phase: 'counting',+ });++ return { success: true, state, isStalled: false };+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-import-from-count-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-import-from-count-or-throw.tsnew file mode 100644index 00000000000..92eb6e1a3b4--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-import-from-count-or-throw.ts@@ -0,0 +1,41 @@+import { kv } from 'twenty-sdk/logic-function';++import { type TeamsTranscriptHistoryRouteResult } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-route-result.type';+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 { scheduleTeamsTranscriptHistoryRunOrThrow } from 'src/features/transcripts/logic-functions/utils/schedule-teams-transcript-history-run-or-throw';++export const startTeamsTranscriptHistoryImportFromCountOrThrow = async ({+ connectedAccountId,+ runId,+}: {+ connectedAccountId: string;+ runId: string;+}): Promise<TeamsTranscriptHistoryRouteResult> => {+ const countedState = await kv.get<TeamsTranscriptHistoryState>(+ buildTeamsTranscriptHistoryKvKey(connectedAccountId),+ );++ if (countedState?.runId !== runId || countedState.phase !== 'counted') {+ return { success: false, errorCode: 'count-required' };+ }++ const state: TeamsTranscriptHistoryState & { phase: 'importing' } = {+ ...countedState,+ phase: 'importing',+ pageCount: 0,+ importedCount: 0,+ skippedCount: 0,+ unavailableCount: 0,+ checkedThrough: undefined,+ updatedAt: new Date().toISOString(),+ };++ await scheduleTeamsTranscriptHistoryRunOrThrow({+ connectedAccountId,+ state,+ stateOnScheduleFailure: countedState,+ });++ return { success: true, state, isStalled: false };+};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.tsindex 1fa4872d03d..03ba5087d40 100644--- 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.ts@@ -1,17 +1,16 @@-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 { buildTeamsTranscriptHistoryInitialImportKvKey } from 'src/features/transcripts/logic-functions/utils/build-teams-transcript-history-initial-import-kv-key';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 { startTeamsTranscriptHistoryRunOrThrow } from 'src/features/transcripts/logic-functions/utils/start-teams-transcript-history-run-or-throw';import { isFeatureEnabled } from 'src/utils/is-feature-enabled';export const startTeamsTranscriptHistoryInitialImportOrThrow = async ({@@ -28,44 +27,31 @@ export const startTeamsTranscriptHistoryInitialImportOrThrow = async ({return;}- const stateKvKey = buildTeamsTranscriptHistoryKvKey(connectedAccountId);- const existingState = await kv.get<TeamsTranscriptHistoryState>(stateKvKey);- const now = Date.now();+ const initialImportKvKey =+ buildTeamsTranscriptHistoryInitialImportKvKey(connectedAccountId);+ const [hasStartedInitialImport, existingState] = await Promise.all([+ kv.get<boolean>(initialImportKvKey),+ kv.get<TeamsTranscriptHistoryState>(+ buildTeamsTranscriptHistoryKvKey(connectedAccountId),+ ),+ ]);if (+ isDefined(hasStartedInitialImport) &&isDefined(existingState) &&- existingState.phase !== 'failed' &&- !isTeamsTranscriptHistoryStalled({ state: existingState, now })+ (existingState.phase !== 'failed' ||+ existingState.errorCode === 'page-limit-reached') &&+ !isTeamsTranscriptHistoryStalled({ state: existingState, now: Date.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(),+ await startTeamsTranscriptHistoryRunOrThrow({+ connectedAccountId,+ days: TEAMS_TRANSCRIPT_HISTORY_INITIAL_IMPORT_DAYS,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;- }+ });+ await kv.set(initialImportKvKey, true);if (!(await isTeamsConnectionListed(connectedAccountId))) {await deleteTeamsTranscriptHistoryKvKeys({ connectedAccountId });diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-run-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-run-or-throw.tsnew file mode 100644index 00000000000..777cb36264b--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/start-teams-transcript-history-run-or-throw.ts@@ -0,0 +1,41 @@+import { randomBytes } from 'node:crypto';++import { MILLISECONDS_PER_DAY } from 'src/features/transcripts/logic-functions/constants/milliseconds-per-day';+import { type TeamsTranscriptHistoryRunningPhase } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-running-phase.type';+import { type TeamsTranscriptHistoryState } from 'src/features/transcripts/logic-functions/types/teams-transcript-history-state.type';+import { scheduleTeamsTranscriptHistoryRunOrThrow } from 'src/features/transcripts/logic-functions/utils/schedule-teams-transcript-history-run-or-throw';++export const startTeamsTranscriptHistoryRunOrThrow = async ({+ connectedAccountId,+ days,+ phase,+}: {+ connectedAccountId: string;+ days: number;+ phase: TeamsTranscriptHistoryRunningPhase;+}): Promise<TeamsTranscriptHistoryState> => {+ const now = Date.now();+ const state = {+ runId: randomBytes(8).toString('hex'),+ days,+ windowStart: new Date(now - days * MILLISECONDS_PER_DAY).toISOString(),+ windowEnd: new Date(now).toISOString(),+ phase,+ transcriptCount: 0,+ alreadyImportedCount: 0,+ deletedCount: 0,+ pageCount: 0,+ importedCount: 0,+ skippedCount: 0,+ unavailableCount: 0,+ updatedAt: new Date(now).toISOString(),+ };++ await scheduleTeamsTranscriptHistoryRunOrThrow({+ connectedAccountId,+ state,+ stateOnScheduleFailure: { ...state, phase: 'failed', errorCode: 'unknown' },+ });++ return state;+};