The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Link Teams transcripts to their calendar event by Microsoft Graph event id (#27676)
nitinc9fd4164fa88
diff --git a/packages/twenty-apps/public/teams/SETUP.md b/packages/twenty-apps/public/teams/SETUP.mdindex 5382fb5de75..a066a260901 100644--- a/packages/twenty-apps/public/teams/SETUP.md+++ b/packages/twenty-apps/public/teams/SETUP.md@@ -66,6 +66,9 @@ connection added while transcripts were off has no subscription: reconnect itafter turning transcripts on. Disconnecting the account or uninstalling the appdeletes the subscription.+Transcripts link to the meeting's calendar event when that calendar is synced in+Twenty. An occurrence of a recurring meeting links to the series' event.+## Test the transcript actions1. For a development build, set `IS_TRANSCRIPT_IMPORT_ENABLED` to `true`, rebuilddiff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-calendar-event-lookup-concurrency.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-calendar-event-lookup-concurrency.tsnew file mode 100644index 00000000000..2403273f5c2--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-calendar-event-lookup-concurrency.ts@@ -0,0 +1 @@+export const TEAMS_CALENDAR_EVENT_LOOKUP_CONCURRENCY = 4;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-occurrence-max-pages.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-occurrence-max-pages.tsnew file mode 100644index 00000000000..5890978389e--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-occurrence-max-pages.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_OCCURRENCE_MAX_PAGES = 5;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-occurrence-page-size.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-occurrence-page-size.tsnew file mode 100644index 00000000000..6f1575c7fb2--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/teams-transcript-occurrence-page-size.ts@@ -0,0 +1 @@+export const TEAMS_TRANSCRIPT_OCCURRENCE_PAGE_SIZE = 1_000;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/twenty-query-max-records.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/twenty-query-max-records.tsnew file mode 100644index 00000000000..3922bafb582--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/constants/twenty-query-max-records.ts@@ -0,0 +1 @@+export const TWENTY_QUERY_MAX_RECORDS = 200;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/calendar-channel-event-association.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/calendar-channel-event-association.type.tsnew file mode 100644index 00000000000..aafabd8cdc1--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/calendar-channel-event-association.type.ts@@ -0,0 +1,4 @@+export type CalendarChannelEventAssociation = {+ eventExternalId: string;+ calendarEventId: string;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/calendar-event.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/calendar-event.type.tsnew file mode 100644index 00000000000..79a9aa715ed--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/calendar-event.type.ts@@ -0,0 +1,4 @@+export type CalendarEvent = {+ id: string;+ iCalUid: string | null;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-calendar-event.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-calendar-event.type.tsindex c3d4ceba068..ea7ea4716f7 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-calendar-event.type.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-calendar-event.type.ts@@ -1,6 +1,9 @@import { type GraphDateTimeTimeZone } from 'src/features/transcripts/logic-functions/types/graph-date-time-time-zone.type';export type TeamsCalendarEvent = {+ id?: string;+ iCalUId?: string | null;+ seriesMasterId?: string | null;isOrganizer?: boolean;isCancelled?: boolean;onlineMeetingProvider?: string;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-calendar-reference.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-calendar-reference.type.tsnew file mode 100644index 00000000000..cdb69325d4c--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-calendar-reference.type.ts@@ -0,0 +1,4 @@+export type TeamsCalendarReference = {+ eventExternalId: string;+ iCalUId?: string;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-meeting-occurrence.type.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-meeting-occurrence.type.tsindex 1710571bfe6..4ee3afdd779 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-meeting-occurrence.type.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/types/teams-meeting-occurrence.type.ts@@ -1,5 +1,7 @@+import { type TeamsCalendarReference } from 'src/features/transcripts/logic-functions/types/teams-calendar-reference.type';import { type TeamsMeetingWindow } from 'src/features/transcripts/logic-functions/types/teams-meeting-window.type';export type TeamsMeetingOccurrence = TeamsMeetingWindow & {joinWebUrl: string;+ calendarReference: TeamsCalendarReference;};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.tsdeleted file mode 100644index 2ad936de7a0..00000000000--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-matching-calendar-event-or-throw.test.ts+++ /dev/null@@ -1,93 +0,0 @@-import { type CoreApiClient } from 'twenty-client-sdk/core';-import { describe, expect, it, vi } from 'vitest';--import { findMatchingCalendarEventOrThrow } from 'src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw';--const JOIN_WEB_URL =- 'https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc%40thread.v2/0';--const buildCoreApiClient = (- calendarEventIds: string[],-): Pick<CoreApiClient, 'query'> => ({- query: vi.fn().mockResolvedValue({- calendarEvents: {- edges: calendarEventIds.map((id) => ({ node: { id } })),- },- }),-});--describe('findMatchingCalendarEventOrThrow', () => {- it('should link the calendar event with the join URL around the transcript start', async () => {- const coreApiClient = buildCoreApiClient(['event-1']);-- await expect(- findMatchingCalendarEventOrThrow({- coreApiClient,- meeting: { joinWebUrl: JOIN_WEB_URL },- transcript: { createdDateTime: '2026-09-05T10:02:00Z' },- }),- ).resolves.toBe('event-1');- expect(coreApiClient.query).toHaveBeenCalledWith({- calendarEvents: expect.objectContaining({- __args: expect.objectContaining({- filter: {- and: [- { conferenceLink: { primaryLinkUrl: { eq: JOIN_WEB_URL } } },- { startsAt: { lte: '2026-09-05T10:17:00.000Z' } },- { endsAt: { gte: '2026-09-05T09:47:00.000Z' } },- { isCanceled: { eq: false } },- ],- },- }),- }),- });- });-- it.each([- ['no', []],- ['several', ['event-1', 'event-2']],- ])(- 'should not link when %s calendar events match',- async (_, calendarEventIds) => {- await expect(- findMatchingCalendarEventOrThrow({- coreApiClient: buildCoreApiClient(calendarEventIds),- meeting: { joinWebUrl: JOIN_WEB_URL },- transcript: { createdDateTime: '2026-09-05T10:02:00Z' },- }),- ).resolves.toBeUndefined();- },- );-- it.each([- [- 'join URL',- { joinWebUrl: null },- { createdDateTime: '2026-09-05T10:02:00Z' },- ],- [- 'transcript start',- { joinWebUrl: JOIN_WEB_URL },- { createdDateTime: null },- ],- [- 'valid transcript start',- { joinWebUrl: JOIN_WEB_URL },- { createdDateTime: 'soon' },- ],- ])(- 'should not query calendar events without a %s',- async (_, meeting, transcript) => {- const coreApiClient = buildCoreApiClient(['event-1']);-- await expect(- findMatchingCalendarEventOrThrow({- coreApiClient,- meeting,- transcript,- }),- ).resolves.toBeUndefined();- expect(coreApiClient.query).not.toHaveBeenCalled();- },- );-});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-calendar-event-ids-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-calendar-event-ids-or-throw.test.tsnew file mode 100644index 00000000000..c9138014377--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-calendar-event-ids-or-throw.test.ts@@ -0,0 +1,162 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { findTeamsCalendarEventIdsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-teams-calendar-event-ids-or-throw';+import { getTeamsCalendarEventICalUIdOrThrow } from 'src/features/transcripts/logic-functions/utils/get-teams-calendar-event-ical-uid-or-throw';++vi.mock(+ 'src/features/transcripts/logic-functions/utils/get-teams-calendar-event-ical-uid-or-throw',+ () => ({ getTeamsCalendarEventICalUIdOrThrow: vi.fn() }),+);++type AssociationNode = { eventExternalId: string; calendarEventId: string };++type QueryRequest = Record<+ string,+ {+ __args: {+ filter: Record<string, { in?: string[] }>;+ after?: string;+ };+ }+>;++const toConnection = <TNode>({+ nodes,+ endCursor,+}: {+ nodes: TNode[];+ endCursor?: string;+}) => ({+ edges: nodes.map((node) => ({ node })),+ pageInfo: {+ hasNextPage: endCursor !== undefined,+ endCursor: endCursor ?? null,+ },+});++describe('findTeamsCalendarEventIdsOrThrow', () => {+ beforeEach(() => {+ vi.mocked(getTeamsCalendarEventICalUIdOrThrow).mockReset();+ });++ it('should not link a reference whose associations point to different events on different pages', async () => {+ vi.mocked(getTeamsCalendarEventICalUIdOrThrow).mockResolvedValue(+ 'ical-series-master-1',+ );+ const query = vi.fn(async (request: QueryRequest) => {+ if ('calendarEvents' in request) {+ return { calendarEvents: toConnection({ nodes: [] }) };+ }++ return {+ calendarChannelEventAssociations: request+ .calendarChannelEventAssociations.__args.after+ ? toConnection<AssociationNode>({+ nodes: [+ {+ eventExternalId: 'series-master-1',+ calendarEventId: 'second-calendar-event',+ },+ ],+ })+ : toConnection<AssociationNode>({+ nodes: [+ {+ eventExternalId: 'series-master-1',+ calendarEventId: 'first-calendar-event',+ },+ ],+ endCursor: 'cursor-1',+ }),+ };+ });++ await expect(+ findTeamsCalendarEventIdsOrThrow({+ accessToken: 'token',+ coreApiClient: { query },+ references: [{ eventExternalId: 'series-master-1' }],+ }),+ ).resolves.toEqual(new Map());+ expect(query).toHaveBeenCalledWith({+ calendarChannelEventAssociations: expect.objectContaining({+ __args: expect.objectContaining({ after: 'cursor-1' }),+ }),+ });+ expect(getTeamsCalendarEventICalUIdOrThrow).toHaveBeenCalledWith({+ accessToken: 'token',+ eventId: 'series-master-1',+ });+ });++ it('should look up more than 200 references in batches and match references from every batch', async () => {+ const references = Array.from({ length: 201 }, (_, index) => ({+ eventExternalId: `event-${index}`,+ }));+ const query = vi.fn(async (request: QueryRequest) => ({+ calendarChannelEventAssociations: toConnection<AssociationNode>({+ nodes: (+ request.calendarChannelEventAssociations.__args.filter.eventExternalId+ .in ?? []+ ).map((eventExternalId) => ({+ eventExternalId,+ calendarEventId: `calendar-${eventExternalId}`,+ })),+ }),+ }));++ const calendarEventIds = await findTeamsCalendarEventIdsOrThrow({+ accessToken: 'token',+ coreApiClient: { query },+ references,+ });++ expect(+ query.mock.calls.map(+ ([request]) =>+ request.calendarChannelEventAssociations.__args.filter.eventExternalId+ .in?.length,+ ),+ ).toEqual([200, 1]);+ expect(calendarEventIds.size).toBe(201);+ expect(calendarEventIds.get('event-200')).toBe('calendar-event-200');+ expect(getTeamsCalendarEventICalUIdOrThrow).not.toHaveBeenCalled();+ });++ it('should read the iCalUIds of unassociated series masters a few at a time', async () => {+ let inFlightCount = 0;+ let maxInFlightCount = 0;++ vi.mocked(getTeamsCalendarEventICalUIdOrThrow).mockImplementation(+ async ({ eventId }) => {+ inFlightCount += 1;+ maxInFlightCount = Math.max(maxInFlightCount, inFlightCount);+ await new Promise((resolve) => setTimeout(resolve, 1));+ inFlightCount -= 1;++ return `ical-${eventId}`;+ },+ );+ const query = vi.fn(async (request: QueryRequest) =>+ 'calendarEvents' in request+ ? { calendarEvents: toConnection({ nodes: [] }) }+ : {+ calendarChannelEventAssociations: toConnection<AssociationNode>({+ nodes: [],+ }),+ },+ );++ await findTeamsCalendarEventIdsOrThrow({+ accessToken: 'token',+ coreApiClient: { query },+ references: Array.from({ length: 10 }, (_, index) => ({+ eventExternalId: `series-master-${index}`,+ })),+ });++ expect(getTeamsCalendarEventICalUIdOrThrow).toHaveBeenCalledTimes(10);+ expect(maxInFlightCount).toBeGreaterThan(1);+ expect(maxInFlightCount).toBeLessThanOrEqual(4);+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-transcript-calendar-event-id-or-throw.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-transcript-calendar-event-id-or-throw.test.tsnew file mode 100644index 00000000000..e4f647f706d--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-transcript-calendar-event-id-or-throw.test.ts@@ -0,0 +1,246 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { fetchGraphJson } from 'src/features/transcripts/logic-functions/utils/fetch-graph-json';+import { findTeamsTranscriptCalendarEventIdOrThrow } from 'src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-event-id-or-throw';++vi.mock(+ 'src/features/transcripts/logic-functions/utils/fetch-graph-json',+ () => ({+ fetchGraphJson: vi.fn(),+ }),+);++const JOIN_WEB_URL =+ 'https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc%40thread.v2/0';++const NEXT_PAGE_URL =+ 'https://graph.microsoft.com/v1.0/me/calendarView?$skip=50';++const TRANSCRIPT = { createdDateTime: '2026-09-19T10:02:00Z' };++const buildCalendarEvent = (overrides: Record<string, unknown> = {}) => ({+ id: 'occurrence-3',+ iCalUId: 'ical-occurrence-3',+ seriesMasterId: 'series-master-1',+ isOrganizer: true,+ isCancelled: false,+ onlineMeetingProvider: 'teamsForBusiness',+ onlineMeeting: { joinUrl: JOIN_WEB_URL },+ start: { dateTime: '2026-09-19T10:00:00.0000000', timeZone: 'UTC' },+ end: { dateTime: '2026-09-19T10:30:00.0000000', timeZone: 'UTC' },+ ...overrides,+});++const mockGraph = (responses: Record<string, unknown>) =>+ vi.mocked(fetchGraphJson).mockImplementation(async ({ url }) => {+ const responseKey = Object.keys(responses).find((key) =>+ url.startsWith(key),+ );+ const response = responseKey === undefined ? {} : responses[responseKey];++ if (response instanceof Error) {+ throw response;+ }++ return response;+ });++const buildCoreApiClient = ({+ associations = [],+ calendarEvents = [],+}: {+ associations?: { eventExternalId: string; calendarEventId: string }[];+ calendarEvents?: { id: string; iCalUid: string }[];+}) => ({+ query: vi.fn().mockImplementation(async (request: object) => {+ const nodes =+ 'calendarChannelEventAssociations' in request+ ? associations+ : calendarEvents;+ const objectName = Object.keys(request)[0];++ return {+ [objectName]: {+ edges: nodes.map((node) => ({ node })),+ pageInfo: { hasNextPage: false, endCursor: null },+ },+ };+ }),+});++describe('findTeamsTranscriptCalendarEventIdOrThrow', () => {+ beforeEach(() => {+ vi.mocked(fetchGraphJson).mockReset();+ vi.spyOn(console, 'error').mockImplementation(() => undefined);+ });++ it('should link an occurrence of a recurring meeting to the series event', async () => {+ mockGraph({+ 'me/calendarView': {+ value: [+ buildCalendarEvent(),+ buildCalendarEvent({+ id: 'other-meeting',+ seriesMasterId: null,+ onlineMeeting: { joinUrl: `${JOIN_WEB_URL}-other` },+ }),+ ],+ },+ });+ const coreApiClient = buildCoreApiClient({+ associations: [+ {+ eventExternalId: 'series-master-1',+ calendarEventId: 'series-calendar-event',+ },+ ],+ });++ await expect(+ findTeamsTranscriptCalendarEventIdOrThrow({+ accessToken: 'token',+ coreApiClient,+ meeting: { joinWebUrl: JOIN_WEB_URL },+ transcript: TRANSCRIPT,+ }),+ ).resolves.toBe('series-calendar-event');+ expect(fetchGraphJson).toHaveBeenCalledWith(+ expect.objectContaining({+ url: expect.stringContaining('%24top=1000'),+ }),+ );+ expect(coreApiClient.query).toHaveBeenCalledTimes(1);+ expect(coreApiClient.query).toHaveBeenCalledWith({+ calendarChannelEventAssociations: expect.objectContaining({+ __args: expect.objectContaining({+ filter: { eventExternalId: { in: ['series-master-1'] } },+ }),+ }),+ });+ });++ it("should fall back on the series master's iCalUId when no association exists", async () => {+ mockGraph({+ 'me/calendarView': { value: [buildCalendarEvent()] },+ 'me/events/series-master-1': { iCalUId: 'ical-series-master-1' },+ });+ const coreApiClient = buildCoreApiClient({+ calendarEvents: [+ { id: 'attendee-calendar-event', iCalUid: 'ical-series-master-1' },+ ],+ });++ await expect(+ findTeamsTranscriptCalendarEventIdOrThrow({+ accessToken: 'token',+ coreApiClient,+ meeting: { joinWebUrl: JOIN_WEB_URL },+ transcript: TRANSCRIPT,+ }),+ ).resolves.toBe('attendee-calendar-event');+ expect(coreApiClient.query).toHaveBeenLastCalledWith({+ calendarEvents: expect.objectContaining({+ __args: expect.objectContaining({+ filter: {+ iCalUid: { in: ['ical-series-master-1'] },+ isCanceled: { eq: false },+ },+ }),+ }),+ });+ });++ it('should find the meeting on a later calendar page', async () => {+ mockGraph({+ [NEXT_PAGE_URL]: { value: [buildCalendarEvent()] },+ 'me/calendarView': {+ value: [],+ '@odata.nextLink': NEXT_PAGE_URL,+ },+ });++ await expect(+ findTeamsTranscriptCalendarEventIdOrThrow({+ accessToken: 'token',+ coreApiClient: buildCoreApiClient({+ associations: [+ {+ eventExternalId: 'series-master-1',+ calendarEventId: 'series-calendar-event',+ },+ ],+ }),+ meeting: { joinWebUrl: JOIN_WEB_URL },+ transcript: TRANSCRIPT,+ }),+ ).resolves.toBe('series-calendar-event');+ });++ it.each([403, 404, 500])(+ 'should leave the transcript unlinked when the calendar lookup answers %s',+ async (status) => {+ mockGraph({+ 'me/calendarView': new GraphRequestError({+ message: `Microsoft Graph request failed (${status})`,+ status,+ innerErrorCode: undefined,+ }),+ });+ const coreApiClient = buildCoreApiClient({});++ await expect(+ findTeamsTranscriptCalendarEventIdOrThrow({+ accessToken: 'token',+ coreApiClient,+ meeting: { joinWebUrl: JOIN_WEB_URL },+ transcript: TRANSCRIPT,+ }),+ ).resolves.toBeUndefined();+ expect(coreApiClient.query).not.toHaveBeenCalled();+ },+ );++ it('should leave the transcript unlinked when the series master cannot be read', async () => {+ mockGraph({+ 'me/calendarView': { value: [buildCalendarEvent()] },+ 'me/events/series-master-1': new GraphRequestError({+ message: 'Microsoft Graph request failed (500)',+ status: 500,+ innerErrorCode: undefined,+ }),+ });++ await expect(+ findTeamsTranscriptCalendarEventIdOrThrow({+ accessToken: 'token',+ coreApiClient: buildCoreApiClient({}),+ meeting: { joinWebUrl: JOIN_WEB_URL },+ transcript: TRANSCRIPT,+ }),+ ).resolves.toBeUndefined();+ });++ it.each([+ ['no join URL', { joinWebUrl: null }, TRANSCRIPT],+ ['no transcript start', { joinWebUrl: JOIN_WEB_URL }, {}],+ [+ 'an invalid transcript start',+ { joinWebUrl: JOIN_WEB_URL },+ { createdDateTime: 'not-a-date' },+ ],+ ])(+ 'should not look up the calendar for a meeting with %s',+ async (_, meeting, transcript) => {+ await expect(+ findTeamsTranscriptCalendarEventIdOrThrow({+ accessToken: 'token',+ coreApiClient: buildCoreApiClient({}),+ meeting,+ transcript,+ }),+ ).resolves.toBeUndefined();+ expect(fetchGraphJson).not.toHaveBeenCalled();+ },+ );+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-transcript-calendar-reference.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-transcript-calendar-reference.test.tsnew file mode 100644index 00000000000..d34564b8713--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/find-teams-transcript-calendar-reference.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest';++import { findTeamsTranscriptCalendarReference } from 'src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-reference';++const JOIN_WEB_URL =+ 'https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc%40thread.v2/0';++const MONDAY_OCCURRENCE = {+ joinWebUrl: JOIN_WEB_URL,+ startDateTime: '2026-09-07T10:00:00.000Z',+ endDateTime: '2026-09-07T10:30:00.000Z',+ calendarReference: { eventExternalId: 'series-master-1' },+};++const TUESDAY_OCCURRENCE = {+ joinWebUrl: JOIN_WEB_URL,+ startDateTime: '2026-09-08T10:00:00.000Z',+ endDateTime: '2026-09-08T10:30:00.000Z',+ calendarReference: { eventExternalId: 'event-2', iCalUId: 'ical-event-2' },+};++describe('findTeamsTranscriptCalendarReference', () => {+ it('should return the reference of the only occurrence around the transcript start', () => {+ expect(+ findTeamsTranscriptCalendarReference({+ transcript: { createdDateTime: '2026-09-08T09:50:00Z' },+ occurrences: [MONDAY_OCCURRENCE, TUESDAY_OCCURRENCE],+ }),+ ).toEqual({ eventExternalId: 'event-2', iCalUId: 'ical-event-2' });+ });++ it('should return nothing when no occurrence or several occurrences match', () => {+ expect(+ findTeamsTranscriptCalendarReference({+ transcript: { createdDateTime: '2026-09-09T10:00:00Z' },+ occurrences: [MONDAY_OCCURRENCE, TUESDAY_OCCURRENCE],+ }),+ ).toBeUndefined();+ expect(+ findTeamsTranscriptCalendarReference({+ transcript: { createdDateTime: '2026-09-08T10:05:00Z' },+ occurrences: [TUESDAY_OCCURRENCE, TUESDAY_OCCURRENCE],+ }),+ ).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/match-teams-calendar-event-ids.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/match-teams-calendar-event-ids.test.tsnew file mode 100644index 00000000000..59452e6d23d--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/match-teams-calendar-event-ids.test.ts@@ -0,0 +1,48 @@+import { describe, expect, it } from 'vitest';++import { matchTeamsCalendarEventIds } from 'src/features/transcripts/logic-functions/utils/match-teams-calendar-event-ids';++describe('matchTeamsCalendarEventIds', () => {+ it('should match a reference through the calendar channel association of its event', () => {+ expect(+ matchTeamsCalendarEventIds({+ references: [{ eventExternalId: 'series-master-1' }],+ calendarChannelEventAssociations: [+ { eventExternalId: 'series-master-1', calendarEventId: 'calendar-1' },+ { eventExternalId: 'series-master-1', calendarEventId: 'calendar-1' },+ { eventExternalId: 'other-event', calendarEventId: 'calendar-2' },+ ],+ calendarEvents: [{ id: 'calendar-3', iCalUid: 'ical-1' }],+ }),+ ).toEqual(new Map([['series-master-1', 'calendar-1']]));+ });++ it('should fall back to the only calendar event with the iCalUId when the association is ambiguous', () => {+ expect(+ matchTeamsCalendarEventIds({+ references: [{ eventExternalId: 'event-1', iCalUId: 'ical-1' }],+ calendarChannelEventAssociations: [+ { eventExternalId: 'event-1', calendarEventId: 'calendar-1' },+ { eventExternalId: 'event-1', calendarEventId: 'calendar-2' },+ ],+ calendarEvents: [+ { id: 'calendar-3', iCalUid: 'ical-1' },+ { id: 'calendar-4', iCalUid: 'ical-2' },+ ],+ }),+ ).toEqual(new Map([['event-1', 'calendar-3']]));+ });++ it('should leave a reference unmatched when several calendar events share its iCalUId', () => {+ expect(+ matchTeamsCalendarEventIds({+ references: [{ eventExternalId: 'event-1', iCalUId: 'ical-1' }],+ calendarChannelEventAssociations: [],+ calendarEvents: [+ { id: 'calendar-1', iCalUid: 'ical-1' },+ { id: 'calendar-2', iCalUid: 'ical-1' },+ ],+ }),+ ).toEqual(new Map());+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/to-teams-meeting-occurrence.test.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/to-teams-meeting-occurrence.test.tsnew file mode 100644index 00000000000..6eb9cdca88a--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/__tests__/to-teams-meeting-occurrence.test.ts@@ -0,0 +1,55 @@+import { describe, expect, it } from 'vitest';++import { toTeamsMeetingOccurrence } from 'src/features/transcripts/logic-functions/utils/to-teams-meeting-occurrence';++const JOIN_WEB_URL =+ 'https://teams.microsoft.com/l/meetup-join/19%3ameeting_abc%40thread.v2/0';++const ORGANIZED_TEAMS_EVENT = {+ id: 'event-1',+ iCalUId: 'ical-event-1',+ isOrganizer: true,+ isCancelled: false,+ onlineMeetingProvider: 'teamsForBusiness',+ onlineMeeting: { joinUrl: JOIN_WEB_URL },+ start: { dateTime: '2026-09-05T10:00:00.0000000', timeZone: 'UTC' },+ end: { dateTime: '2026-09-05T10:30:00.0000000', timeZone: 'UTC' },+};++describe('toTeamsMeetingOccurrence', () => {+ it('should reference a single meeting by its own event id and iCalUId', () => {+ expect(toTeamsMeetingOccurrence(ORGANIZED_TEAMS_EVENT)).toEqual({+ joinWebUrl: JOIN_WEB_URL,+ startDateTime: '2026-09-05T10:00:00.000Z',+ endDateTime: '2026-09-05T10:30:00.000Z',+ calendarReference: {+ eventExternalId: 'event-1',+ iCalUId: 'ical-event-1',+ },+ });+ });++ it('should reference an occurrence of a recurring meeting by its series master', () => {+ expect(+ toTeamsMeetingOccurrence({+ ...ORGANIZED_TEAMS_EVENT,+ id: 'occurrence-1',+ iCalUId: 'ical-occurrence-1',+ seriesMasterId: 'series-master-1',+ })?.calendarReference,+ ).toEqual({ eventExternalId: 'series-master-1' });+ });++ it.each([+ ['not organized by the account', { isOrganizer: false }],+ ['cancelled', { isCancelled: true }],+ ['not a Teams meeting', { onlineMeetingProvider: 'skypeForBusiness' }],+ ['without a join URL', { onlineMeeting: null }],+ ['without an id', { id: undefined }],+ ['without an end', { end: null }],+ ])('should skip an event %s', (_, eventOverrides) => {+ expect(+ toTeamsMeetingOccurrence({ ...ORGANIZED_TEAMS_EVENT, ...eventOverrides }),+ ).toBeUndefined();+ });+});diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-calendar-view-url.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-calendar-view-url.tsindex 275db18c14e..f2914372e5e 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-calendar-view-url.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/build-teams-calendar-view-url.ts@@ -1,15 +1,17 @@import { TEAMS_CALENDAR_PAGE_SIZE } from 'src/features/transcripts/logic-functions/constants/teams-calendar-page-size';import { type TeamsMeetingWindow } from 'src/features/transcripts/logic-functions/types/teams-meeting-window.type';-export const buildTeamsCalendarViewUrl = (- window: TeamsMeetingWindow,-): string => {+export const buildTeamsCalendarViewUrl = ({+ startDateTime,+ endDateTime,+ pageSize = TEAMS_CALENDAR_PAGE_SIZE,+}: TeamsMeetingWindow & { pageSize?: number }): string => {const query = new URLSearchParams({- startDateTime: window.startDateTime,- endDateTime: window.endDateTime,+ startDateTime,+ endDateTime,$select:- 'isOrganizer,isCancelled,onlineMeetingProvider,onlineMeeting,start,end',- $top: String(TEAMS_CALENDAR_PAGE_SIZE),+ 'id,iCalUId,seriesMasterId,isOrganizer,isCancelled,onlineMeetingProvider,onlineMeeting,start,end',+ $top: String(pageSize),});return `me/calendarView?${query}`;diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/chunk-into-batches.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/chunk-into-batches.tsnew file mode 100644index 00000000000..62e4d1e54fc--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/chunk-into-batches.ts@@ -0,0 +1,7 @@+export const chunkIntoBatches = <TItem>(+ items: TItem[],+ batchSize: number,+): TItem[][] =>+ Array.from({ length: Math.ceil(items.length / batchSize) }, (_, batchIndex) =>+ items.slice(batchIndex * batchSize, (batchIndex + 1) * batchSize),+ );diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw.tsdeleted file mode 100644index ab05e864bcf..00000000000--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw.ts+++ /dev/null@@ -1,72 +0,0 @@-import { isNonEmptyString } from '@sniptt/guards';-import { type CoreApiClient } from 'twenty-client-sdk/core';--import { TEAMS_OCCURRENCE_MARGIN_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-occurrence-margin-milliseconds';-import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';-import { type GraphOnlineMeeting } from 'src/features/transcripts/logic-functions/types/graph-online-meeting.type';--type CalendarEventMatches = {- edges: { node: { id: string } }[];-};--export const findMatchingCalendarEventOrThrow = async ({- coreApiClient,- meeting,- transcript,-}: {- coreApiClient: Pick<CoreApiClient, 'query'>;- meeting: Pick<GraphOnlineMeeting, 'joinWebUrl'>;- transcript: Pick<GraphCallTranscript, 'createdDateTime'>;-}): Promise<string | undefined> => {- if (- !isNonEmptyString(meeting.joinWebUrl) ||- !isNonEmptyString(transcript.createdDateTime)- ) {- return undefined;- }-- const transcriptStartMilliseconds = Date.parse(transcript.createdDateTime);-- if (!Number.isFinite(transcriptStartMilliseconds)) {- return undefined;- }-- // Every occurrence of a recurring meeting shares one join URL, so the- // transcript start picks the occurrence, with the same margin as listing.- const result = await coreApiClient.query({- calendarEvents: {- __args: {- filter: {- and: [- { conferenceLink: { primaryLinkUrl: { eq: meeting.joinWebUrl } } },- {- startsAt: {- lte: new Date(- transcriptStartMilliseconds +- TEAMS_OCCURRENCE_MARGIN_MILLISECONDS,- ).toISOString(),- },- },- {- endsAt: {- gte: new Date(- transcriptStartMilliseconds -- TEAMS_OCCURRENCE_MARGIN_MILLISECONDS,- ).toISOString(),- },- },- { isCanceled: { eq: false } },- ],- },- first: 2,- },- edges: { node: { id: true } },- },- });- const calendarEvents: CalendarEventMatches | undefined =- result.calendarEvents;-- return calendarEvents?.edges.length === 1- ? calendarEvents.edges[0].node.id- : undefined;-};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-calendar-event-ids-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-calendar-event-ids-or-throw.tsnew file mode 100644index 00000000000..e08e6ac8f2e--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-calendar-event-ids-or-throw.ts@@ -0,0 +1,221 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'twenty-sdk/utils';++import { TEAMS_CALENDAR_EVENT_LOOKUP_CONCURRENCY } from 'src/features/transcripts/logic-functions/constants/teams-calendar-event-lookup-concurrency';+import { TWENTY_QUERY_MAX_RECORDS } from 'src/features/transcripts/logic-functions/constants/twenty-query-max-records';+import { type CalendarChannelEventAssociation } from 'src/features/transcripts/logic-functions/types/calendar-channel-event-association.type';+import { type CalendarEvent } from 'src/features/transcripts/logic-functions/types/calendar-event.type';+import { type TeamsCalendarReference } from 'src/features/transcripts/logic-functions/types/teams-calendar-reference.type';+import { chunkIntoBatches } from 'src/features/transcripts/logic-functions/utils/chunk-into-batches';+import { getTeamsCalendarEventICalUIdOrThrow } from 'src/features/transcripts/logic-functions/utils/get-teams-calendar-event-ical-uid-or-throw';+import { groupCalendarEventIdsByKey } from 'src/features/transcripts/logic-functions/utils/group-calendar-event-ids-by-key';+import { matchTeamsCalendarEventIds } from 'src/features/transcripts/logic-functions/utils/match-teams-calendar-event-ids';++type RecordConnection<TNode> = {+ edges: { node: TNode }[];+ pageInfo: { hasNextPage: boolean; endCursor: string | null };+};++const listAllNodesOrThrow = async <TNode>({+ coreApiClient,+ objectName,+ filter,+ node,+ after,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ objectName: 'calendarChannelEventAssociations' | 'calendarEvents';+ filter: Record<string, unknown>;+ node: Record<keyof TNode, true>;+ after?: string;+}): Promise<TNode[]> => {+ const result = await coreApiClient.query({+ [objectName]: {+ __args: {+ filter,+ first: TWENTY_QUERY_MAX_RECORDS,+ ...(isDefined(after) ? { after } : {}),+ },+ edges: { node },+ pageInfo: { hasNextPage: true, endCursor: true },+ },+ });+ const connection: RecordConnection<TNode> | undefined = result[objectName];+ const nodes = connection?.edges.map((edge) => edge.node) ?? [];+ const endCursor = connection?.pageInfo.endCursor;++ if (!connection?.pageInfo.hasNextPage || !isNonEmptyString(endCursor)) {+ return nodes;+ }++ return [+ ...nodes,+ ...(await listAllNodesOrThrow({+ coreApiClient,+ objectName,+ filter,+ node,+ after: endCursor,+ })),+ ];+};++const listAllNodesInBatchesOrThrow = async <TNode>({+ coreApiClient,+ objectName,+ values,+ buildFilter,+ node,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ objectName: 'calendarChannelEventAssociations' | 'calendarEvents';+ values: string[];+ buildFilter: (batch: string[]) => Record<string, unknown>;+ node: Record<keyof TNode, true>;+}): Promise<TNode[]> => {+ const nodes: TNode[] = [];++ for (const batch of chunkIntoBatches(values, TWENTY_QUERY_MAX_RECORDS)) {+ nodes.push(+ ...(await listAllNodesOrThrow<TNode>({+ coreApiClient,+ objectName,+ filter: buildFilter(batch),+ node,+ })),+ );+ }++ return nodes;+};++const listCalendarChannelEventAssociationsOrThrow = ({+ coreApiClient,+ eventExternalIds,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ eventExternalIds: string[];+}): Promise<CalendarChannelEventAssociation[]> =>+ listAllNodesInBatchesOrThrow<CalendarChannelEventAssociation>({+ coreApiClient,+ objectName: 'calendarChannelEventAssociations',+ values: eventExternalIds,+ buildFilter: (eventExternalIdBatch) => ({+ eventExternalId: { in: eventExternalIdBatch },+ }),+ node: { eventExternalId: true, calendarEventId: true },+ });++const listCalendarEventsByICalUidOrThrow = ({+ coreApiClient,+ iCalUIds,+}: {+ coreApiClient: Pick<CoreApiClient, 'query'>;+ iCalUIds: string[];+}): Promise<CalendarEvent[]> =>+ listAllNodesInBatchesOrThrow<CalendarEvent>({+ coreApiClient,+ objectName: 'calendarEvents',+ values: iCalUIds,+ buildFilter: (iCalUIdBatch) => ({+ iCalUid: { in: iCalUIdBatch },+ isCanceled: { eq: false },+ }),+ node: { id: true, iCalUid: true },+ });++const addMissingICalUIdsOrThrow = async ({+ accessToken,+ references,+}: {+ accessToken: string;+ references: TeamsCalendarReference[];+}): Promise<TeamsCalendarReference[]> => {+ const missingEventExternalIds = [+ ...new Set(+ references+ .filter(({ iCalUId }) => !isDefined(iCalUId))+ .map(({ eventExternalId }) => eventExternalId),+ ),+ ];+ const iCalUIdsByEventExternalId = new Map<string, string | undefined>();++ for (const eventExternalIdBatch of chunkIntoBatches(+ missingEventExternalIds,+ TEAMS_CALENDAR_EVENT_LOOKUP_CONCURRENCY,+ )) {+ const iCalUIds = await Promise.all(+ eventExternalIdBatch.map((eventId) =>+ getTeamsCalendarEventICalUIdOrThrow({ accessToken, eventId }),+ ),+ );++ eventExternalIdBatch.forEach((eventExternalId, index) =>+ iCalUIdsByEventExternalId.set(eventExternalId, iCalUIds[index]),+ );+ }++ return references.map((reference) =>+ isDefined(reference.iCalUId)+ ? reference+ : {+ ...reference,+ iCalUId: iCalUIdsByEventExternalId.get(reference.eventExternalId),+ },+ );+};++export const findTeamsCalendarEventIdsOrThrow = async ({+ accessToken,+ coreApiClient,+ references,+}: {+ accessToken: string;+ coreApiClient: Pick<CoreApiClient, 'query'>;+ references: TeamsCalendarReference[];+}): Promise<Map<string, string>> => {+ const calendarChannelEventAssociations =+ await listCalendarChannelEventAssociationsOrThrow({+ coreApiClient,+ eventExternalIds: [+ ...new Set(references.map(({ eventExternalId }) => eventExternalId)),+ ],+ });+ const calendarEventIdsByEventExternalId = groupCalendarEventIdsByKey(+ calendarChannelEventAssociations.map(+ ({ eventExternalId, calendarEventId }): [string, string] => [+ eventExternalId,+ calendarEventId,+ ],+ ),+ );+ const isUniquelyAssociated = ({ eventExternalId }: TeamsCalendarReference) =>+ calendarEventIdsByEventExternalId.get(eventExternalId)?.size === 1;+ const uniquelyAssociatedReferences = references.filter(isUniquelyAssociated);+ const iCalUIdFallbackReferences = await addMissingICalUIdsOrThrow({+ accessToken,+ references: references.filter(+ (reference) => !isUniquelyAssociated(reference),+ ),+ });+ const fallbackICalUIds = [+ ...new Set(+ iCalUIdFallbackReferences+ .map(({ iCalUId }) => iCalUId)+ .filter(isNonEmptyString),+ ),+ ];++ return matchTeamsCalendarEventIds({+ references: [...uniquelyAssociatedReferences, ...iCalUIdFallbackReferences],+ calendarChannelEventAssociations,+ calendarEvents:+ fallbackICalUIds.length > 0+ ? await listCalendarEventsByICalUidOrThrow({+ coreApiClient,+ iCalUIds: fallbackICalUIds,+ })+ : [],+ });+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-event-id-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-event-id-or-throw.tsnew file mode 100644index 00000000000..896891f04fa--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-event-id-or-throw.ts@@ -0,0 +1,130 @@+import { isNonEmptyString } from '@sniptt/guards';+import { type CoreApiClient } from 'twenty-client-sdk/core';+import { isDefined } from 'twenty-sdk/utils';++import { TEAMS_OCCURRENCE_MARGIN_MILLISECONDS } from 'src/features/transcripts/logic-functions/constants/teams-occurrence-margin-milliseconds';+import { TEAMS_TRANSCRIPT_OCCURRENCE_MAX_PAGES } from 'src/features/transcripts/logic-functions/constants/teams-transcript-occurrence-max-pages';+import { TEAMS_TRANSCRIPT_OCCURRENCE_PAGE_SIZE } from 'src/features/transcripts/logic-functions/constants/teams-transcript-occurrence-page-size';+import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';+import { type GraphOnlineMeeting } from 'src/features/transcripts/logic-functions/types/graph-online-meeting.type';+import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { type TeamsMeetingOccurrence } from 'src/features/transcripts/logic-functions/types/teams-meeting-occurrence.type';+import { buildTeamsCalendarViewUrl } from 'src/features/transcripts/logic-functions/utils/build-teams-calendar-view-url';+import { findTeamsCalendarEventIdsOrThrow } from 'src/features/transcripts/logic-functions/utils/find-teams-calendar-event-ids-or-throw';+import { findTeamsTranscriptCalendarReference } from 'src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-reference';+import { listTeamsCalendarPage } from 'src/features/transcripts/logic-functions/utils/list-teams-calendar-page';+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';++const listOccurrencePagesOrThrow = async ({+ accessToken,+ url,+ pageIndex,+}: {+ accessToken: string;+ url: string;+ pageIndex: number;+}): Promise<TeamsMeetingOccurrence[]> => {+ const { occurrences, nextPageUrl } = await listTeamsCalendarPage({+ accessToken,+ url,+ });++ if (+ !isDefined(nextPageUrl) ||+ pageIndex + 1 >= TEAMS_TRANSCRIPT_OCCURRENCE_MAX_PAGES+ ) {+ return occurrences;+ }++ return [+ ...occurrences,+ ...(await listOccurrencePagesOrThrow({+ accessToken,+ url: resolveTeamsCalendarNextPageUrlOrThrow(nextPageUrl),+ pageIndex: pageIndex + 1,+ })),+ ];+};++const listOccurrencesAroundTranscriptStartOrThrow = async ({+ accessToken,+ transcriptStartMilliseconds,+}: {+ accessToken: string;+ transcriptStartMilliseconds: number;+}): Promise<TeamsMeetingOccurrence[]> => {+ try {+ return await listOccurrencePagesOrThrow({+ accessToken,+ url: buildTeamsCalendarViewUrl({+ startDateTime: new Date(+ transcriptStartMilliseconds - TEAMS_OCCURRENCE_MARGIN_MILLISECONDS,+ ).toISOString(),+ endDateTime: new Date(+ transcriptStartMilliseconds + TEAMS_OCCURRENCE_MARGIN_MILLISECONDS,+ ).toISOString(),+ pageSize: TEAMS_TRANSCRIPT_OCCURRENCE_PAGE_SIZE,+ }),+ pageIndex: 0,+ });+ } catch (error) {+ if (!(error instanceof GraphRequestError)) {+ throw error;+ }++ console.error(+ `[teams] could not list the calendar to link a transcript to its event: ${toErrorMessage(error)}`,+ );++ return [];+ }+};++export const findTeamsTranscriptCalendarEventIdOrThrow = async ({+ accessToken,+ coreApiClient,+ meeting,+ transcript,+}: {+ accessToken: string;+ coreApiClient: Pick<CoreApiClient, 'query'>;+ meeting: Pick<GraphOnlineMeeting, 'joinWebUrl'>;+ transcript: Pick<GraphCallTranscript, 'createdDateTime'>;+}): Promise<string | undefined> => {+ if (+ !isNonEmptyString(meeting.joinWebUrl) ||+ !isNonEmptyString(transcript.createdDateTime)+ ) {+ return undefined;+ }++ const transcriptStartMilliseconds = Date.parse(transcript.createdDateTime);++ if (!Number.isFinite(transcriptStartMilliseconds)) {+ return undefined;+ }++ const occurrences = await listOccurrencesAroundTranscriptStartOrThrow({+ accessToken,+ transcriptStartMilliseconds,+ });+ const calendarReference = findTeamsTranscriptCalendarReference({+ transcript,+ occurrences: occurrences.filter(+ (occurrence) => occurrence.joinWebUrl === meeting.joinWebUrl,+ ),+ });++ if (!isDefined(calendarReference)) {+ return undefined;+ }++ const calendarEventIds = await findTeamsCalendarEventIdsOrThrow({+ accessToken,+ coreApiClient,+ references: [calendarReference],+ });++ return calendarEventIds.get(calendarReference.eventExternalId);+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-reference.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-reference.tsnew file mode 100644index 00000000000..46745a98bbf--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-reference.ts@@ -0,0 +1,20 @@+import { type GraphCallTranscript } from 'src/features/transcripts/logic-functions/types/graph-call-transcript.type';+import { type TeamsCalendarReference } from 'src/features/transcripts/logic-functions/types/teams-calendar-reference.type';+import { type TeamsMeetingOccurrence } from 'src/features/transcripts/logic-functions/types/teams-meeting-occurrence.type';+import { isTranscriptDuringOccurrence } from 'src/features/transcripts/logic-functions/utils/is-transcript-during-occurrence';++export const findTeamsTranscriptCalendarReference = ({+ transcript,+ occurrences,+}: {+ transcript: Pick<GraphCallTranscript, 'createdDateTime'>;+ occurrences: TeamsMeetingOccurrence[];+}): TeamsCalendarReference | undefined => {+ const matchingOccurrences = occurrences.filter((occurrence) =>+ isTranscriptDuringOccurrence({ transcript, occurrence }),+ );++ return matchingOccurrences.length === 1+ ? matchingOccurrences[0].calendarReference+ : undefined;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-calendar-event-ical-uid-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-calendar-event-ical-uid-or-throw.tsnew file mode 100644index 00000000000..376ce5d8445--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/get-teams-calendar-event-ical-uid-or-throw.ts@@ -0,0 +1,33 @@+import { isNonEmptyString } from '@sniptt/guards';++import { GraphRequestError } from 'src/features/transcripts/logic-functions/types/graph-request-error';+import { type TeamsCalendarEvent } from 'src/features/transcripts/logic-functions/types/teams-calendar-event.type';+import { fetchGraphJson } from 'src/features/transcripts/logic-functions/utils/fetch-graph-json';+import { toErrorMessage } from 'src/utils/to-error-message';++export const getTeamsCalendarEventICalUIdOrThrow = async ({+ accessToken,+ eventId,+}: {+ accessToken: string;+ eventId: string;+}): Promise<string | undefined> => {+ try {+ const event = await fetchGraphJson<Pick<TeamsCalendarEvent, 'iCalUId'>>({+ accessToken,+ url: `me/events/${encodeURIComponent(eventId)}?$select=iCalUId`,+ });++ return isNonEmptyString(event.iCalUId) ? event.iCalUId : undefined;+ } catch (error) {+ if (!(error instanceof GraphRequestError)) {+ throw error;+ }++ console.error(+ `[teams] could not read the iCalUId of calendar event ${eventId}: ${toErrorMessage(error)}`,+ );++ return undefined;+ }+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/group-calendar-event-ids-by-key.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/group-calendar-event-ids-by-key.tsnew file mode 100644index 00000000000..d6ecfbbdf45--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/group-calendar-event-ids-by-key.ts@@ -0,0 +1,16 @@+export const groupCalendarEventIdsByKey = (+ entries: [string, string][],+): Map<string, Set<string>> => {+ const calendarEventIdsByKey = new Map<string, Set<string>>();++ for (const [key, calendarEventId] of entries) {+ calendarEventIdsByKey.set(+ key,+ (calendarEventIdsByKey.get(key) ?? new Set<string>()).add(+ calendarEventId,+ ),+ );+ }++ return calendarEventIdsByKey;+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/match-teams-calendar-event-ids.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/match-teams-calendar-event-ids.tsnew file mode 100644index 00000000000..3910bf1bc9e--- /dev/null+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/match-teams-calendar-event-ids.ts@@ -0,0 +1,52 @@+import { isNonEmptyString } from '@sniptt/guards';+import { isDefined } from 'twenty-sdk/utils';++import { type CalendarChannelEventAssociation } from 'src/features/transcripts/logic-functions/types/calendar-channel-event-association.type';+import { type CalendarEvent } from 'src/features/transcripts/logic-functions/types/calendar-event.type';+import { type TeamsCalendarReference } from 'src/features/transcripts/logic-functions/types/teams-calendar-reference.type';+import { groupCalendarEventIdsByKey } from 'src/features/transcripts/logic-functions/utils/group-calendar-event-ids-by-key';++const findUniqueCalendarEventId = (+ calendarEventIds: Set<string> | undefined,+): string | undefined =>+ calendarEventIds?.size === 1 ? [...calendarEventIds][0] : undefined;++export const matchTeamsCalendarEventIds = ({+ references,+ calendarChannelEventAssociations,+ calendarEvents,+}: {+ references: TeamsCalendarReference[];+ calendarChannelEventAssociations: CalendarChannelEventAssociation[];+ calendarEvents: CalendarEvent[];+}): Map<string, string> => {+ const calendarEventIdsByEventExternalId = groupCalendarEventIdsByKey(+ calendarChannelEventAssociations.map(+ ({ eventExternalId, calendarEventId }): [string, string] => [+ eventExternalId,+ calendarEventId,+ ],+ ),+ );+ const calendarEventIdsByICalUid = groupCalendarEventIdsByKey(+ calendarEvents.flatMap(({ id, iCalUid }): [string, string][] =>+ isNonEmptyString(iCalUid) ? [[iCalUid, id]] : [],+ ),+ );++ return new Map(+ references.flatMap(({ eventExternalId, iCalUId }): [string, string][] => {+ const calendarEventId =+ findUniqueCalendarEventId(+ calendarEventIdsByEventExternalId.get(eventExternalId),+ ) ??+ (isDefined(iCalUId)+ ? findUniqueCalendarEventId(calendarEventIdsByICalUid.get(iCalUId))+ : undefined);++ return isDefined(calendarEventId)+ ? [[eventExternalId, calendarEventId]]+ : [];+ }),+ );+};diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.tsindex dfe432bf2d5..d04f14a7d84 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/sync-teams-transcript-to-call-recording-or-throw.ts@@ -4,7 +4,7 @@ import { type CallRecordingSyncFields } from 'src/features/transcripts/logic-funimport { buildTeamsCallRecordingSyncFields } from 'src/features/transcripts/logic-functions/utils/build-teams-call-recording-sync-fields';import { computeCallRecordingIdForTeamsTranscript } from 'src/features/transcripts/logic-functions/utils/compute-call-recording-id-for-teams-transcript';import { fetchTeamsTranscriptData } from 'src/features/transcripts/logic-functions/utils/fetch-teams-transcript-data';-import { findMatchingCalendarEventOrThrow } from 'src/features/transcripts/logic-functions/utils/find-matching-calendar-event-or-throw';+import { findTeamsTranscriptCalendarEventIdOrThrow } from 'src/features/transcripts/logic-functions/utils/find-teams-transcript-calendar-event-id-or-throw';import { mapTeamsTranscriptToEntries } from 'src/features/transcripts/logic-functions/utils/map-teams-transcript-to-entries';import { upsertCallRecordingOrThrow } from 'src/features/transcripts/logic-functions/utils/upsert-call-recording-or-throw';@@ -31,7 +31,8 @@ export const syncTeamsTranscriptToCallRecordingOrThrow = async ({const callRecordingId = computeCallRecordingIdForTeamsTranscript(transcript.id,);- const calendarEventId = await findMatchingCalendarEventOrThrow({+ const calendarEventId = await findTeamsTranscriptCalendarEventIdOrThrow({+ accessToken,coreApiClient,meeting,transcript,diff --git a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-teams-meeting-occurrence.ts b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-teams-meeting-occurrence.tsindex d71d7f9fe4a..bb4aaa826a0 100644--- a/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-teams-meeting-occurrence.ts+++ b/packages/twenty-apps/public/teams/src/features/transcripts/logic-functions/utils/to-teams-meeting-occurrence.ts@@ -17,11 +17,19 @@ export const toTeamsMeetingOccurrence = (event.isCancelled ||event.onlineMeetingProvider !== 'teamsForBusiness' ||!isNonEmptyString(joinWebUrl) ||+ !isNonEmptyString(event.id) ||!isDefined(startDateTime) ||!isDefined(endDateTime)) {return undefined;}- return { joinWebUrl, startDateTime, endDateTime };+ const calendarReference = isNonEmptyString(event.seriesMasterId)+ ? { eventExternalId: event.seriesMasterId }+ : {+ eventExternalId: event.id,+ ...(isNonEmptyString(event.iCalUId) ? { iCalUId: event.iCalUId } : {}),+ };++ return { joinWebUrl, startDateTime, endDateTime, calendarReference };};diff --git a/packages/twenty-apps/public/teams/src/roles/default-function.role.ts b/packages/twenty-apps/public/teams/src/roles/default-function.role.tsindex 82b5aa32362..c5ba70300d3 100644--- a/packages/twenty-apps/public/teams/src/roles/default-function.role.ts+++ b/packages/twenty-apps/public/teams/src/roles/default-function.role.ts@@ -11,7 +11,7 @@ export default defineApplicationRole({universalIdentifier: DEFAULT_ROLE_UNIVERSAL_IDENTIFIER,label: 'Twenty Microsoft Teams tools role',description:- 'Reads calendar events to match Teams meetings and writes imported transcripts to Call Recordings. Tracks assistant requests received from Teams, reads workspace members to match a Teams sender by email, and runs the Teams Assistant agent as that member, with the permissions of that member. Chat tools only forward requests to Microsoft Teams using the configured bot credentials.',+ 'Reads calendar events and their calendar channel associations to match Teams meetings and writes imported transcripts to Call Recordings. Tracks assistant requests received from Teams, reads workspace members to match a Teams sender by email, and runs the Teams Assistant agent as that member, with the permissions of that member. Chat tools only forward requests to Microsoft Teams using the configured bot credentials.',canReadAllObjectRecords: false,canUpdateAllObjectRecords: false,canSoftDeleteAllObjectRecords: false,@@ -29,6 +29,15 @@ export default defineApplicationRole({canSoftDeleteObjectRecords: false,canDestroyObjectRecords: false,},+ {+ objectUniversalIdentifier:+ STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.calendarChannelEventAssociation+ .universalIdentifier,+ canReadObjectRecords: true,+ canUpdateObjectRecords: false,+ canSoftDeleteObjectRecords: false,+ canDestroyObjectRecords: false,+ },{objectUniversalIdentifier:STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.callRecording.universalIdentifier,