The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
test(server): cover outbound messaging and calendar providers (#24164)
neo7736a7755d69a7a
diff --git a/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts b/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.tsindex e535f2eb4ff..51675be6697 100644--- a/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts+++ b/packages/twenty-server/test/integration/caldav/suites/caldav-events-import.integration-spec.ts@@ -8,6 +8,7 @@ import { CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-chanimport { deleteConnectedAccount } from 'test/integration/metadata/suites/connected-account/utils/delete-connected-account.util';import { saveImapSmtpCaldavAccount } from 'test/integration/metadata/suites/connected-account/utils/save-imap-smtp-caldav-account.util';import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.util';+import { createCalendarEvent } from 'test/integration/utils/create-calendar-event.util';import { findImportedCalendarEventTitles } from 'test/integration/utils/find-imported-records.util';import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';import { runCalendarChannelEventsImport } from 'test/integration/utils/run-calendar-channel-events-import.util';@@ -158,6 +159,33 @@ describe('CalDAV calendar events import (integration)', () => {expect(await findImportedCalendarEventTitles([summary])).toEqual([summary]);}, 300000);+ it('creates and persists an event in the CalDAV collection', async () => {+ const title = `CalDAV calendar outbound ${randomUUID()}`;++ const result = await createCalendarEvent({+ connectedAccountId,+ title,+ description: 'Planning meeting',+ location: 'Room 101',+ startsAt: '2026-08-13T09:00:00Z',+ endsAt: '2026-08-13T10:00:00Z',+ timeZone: 'UTC',+ attendees: '[email protected]',+ sendInvitations: true,+ });++ expect(result).toMatchObject({ success: true });+ expect(result.iCalUid).toBeDefined();+ expect(await findImportedCalendarEventTitles([title])).toEqual([title]);++ const response = await fetch(`${collectionUrl()}${result.iCalUid}.ics`, {+ headers: { Authorization: authorizationHeader },+ });++ expect(response.status).toBe(200);+ expect(await response.text()).toContain(`SUMMARY:${title}`);+ }, 300000);+it('advances the sync token and imports an event added afterwards', async () => {const firstSummary = `CalDAV event ${randomUUID()}`;const secondSummary = `CalDAV event ${randomUUID()}`;diff --git a/packages/twenty-server/test/integration/google/messaging/outbound.integration-spec.ts b/packages/twenty-server/test/integration/google/messaging/outbound.integration-spec.tsnew file mode 100644index 00000000000..21964a3eba1--- /dev/null+++ b/packages/twenty-server/test/integration/google/messaging/outbound.integration-spec.ts@@ -0,0 +1,251 @@+import { randomUUID } from 'node:crypto';++import { ConnectedAccountProvider } from 'twenty-shared/types';++import { gmailMessage } from 'test/integration/google/mocks/gmail-message.util';+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';+import { createCalendarEvent } from 'test/integration/utils/create-calendar-event.util';+import { findImportedCalendarEventTitles } from 'test/integration/utils/find-imported-records.util';+import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';+import { sendEmail } from 'test/integration/utils/send-email.util';++const HANDLE = '[email protected]';+const RECIPIENTS = {+ to: '[email protected]',+ cc: '[email protected]',+ bcc: '[email protected]',+};+const PARENT_MESSAGE = gmailMessage({+ id: 'gmail-parent',+ threadId: 'gmail-parent-thread',+ to: HANDLE,+});+const DRAFT_SUBJECT = `Gmail draft ${randomUUID()}`;+const DRAFT_MESSAGE = gmailMessage({+ id: 'gmail-draft-message',+ threadId: 'gmail-draft-thread',+ from: HANDLE,+ to: RECIPIENTS.to,+ labelIds: ['DRAFT'],+ payload: {+ mimeType: 'text/plain',+ headers: [+ { name: 'From', value: HANDLE },+ { name: 'To', value: RECIPIENTS.to },+ { name: 'Cc', value: RECIPIENTS.cc },+ { name: 'Bcc', value: RECIPIENTS.bcc },+ { name: 'Subject', value: DRAFT_SUBJECT },+ { name: 'Message-ID', value: '<[email protected]>' },+ { name: 'Date', value: 'Wed, 15 Nov 2023 00:00:00 +0000' },+ ],+ body: {+ data: Buffer.from('Gmail draft body').toString('base64'),+ size: 16,+ },+ },+});++describe('Gmail outbound messaging and calendar creation (integration)', () => {+ const google = setupGoogleMock({+ handle: HANDLE,+ inbox: [PARENT_MESSAGE, DRAFT_MESSAGE],+ });++ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;++ beforeAll(async () => {+ channel = await connectMessagingAccount({+ provider: ConnectedAccountProvider.GOOGLE,+ handle: HANDLE,+ });+ await runMessageChannelSync(channel.channelId);+ }, 60000);++ afterAll(async () => {+ await channel?.cleanup().catch(() => undefined);+ });++ it('sends a reply with recipients and RFC 5322 threading headers', async () => {+ const subject = `Gmail outbound ${randomUUID()}`;++ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ to: RECIPIENTS.to,+ cc: RECIPIENTS.cc,+ bcc: RECIPIENTS.bcc,+ subject,+ body: '<p>Gmail reply body</p>',+ inReplyTo: '<[email protected]>',+ });++ expect(result).toMatchObject({ success: true });+ expect(google.sentMessages).toHaveLength(1);++ const [{ raw, threadId }] = google.sentMessages;++ expect(threadId).toBe(PARENT_MESSAGE.threadId);+ expect(raw).toContain(`To: ${RECIPIENTS.to}`);+ expect(raw).toContain(`Cc: ${RECIPIENTS.cc}`);+ expect(raw).toContain(`Bcc: ${RECIPIENTS.bcc}`);+ expect(raw).toContain(`Subject: ${subject}`);+ expect(raw).toContain('In-Reply-To: <[email protected]>');+ expect(raw).toContain('References: <[email protected]>');++ const [message] = await findRecordNodesByFilter<{+ id: string;+ isDraft: boolean;+ messageThreadId: string | null;+ text: string | null;+ }>('message', 'messages', 'id isDraft messageThreadId text', {+ subject: { eq: subject },+ });++ expect(message).toMatchObject({+ isDraft: false,+ messageThreadId: expect.any(String),+ text: 'Gmail reply body',+ });+ expect(+ await findRecordNodesByFilter<{+ messageChannelId: string;+ }>(+ 'messageChannelMessageAssociation',+ 'messageChannelMessageAssociations',+ 'messageChannelId',+ { messageId: { eq: message.id } },+ ),+ ).toEqual([+ expect.objectContaining({ messageChannelId: channel.channelId }),+ ]);+ expect(+ await findRecordNodesByFilter<{ handle: string; role: string }>(+ 'messageParticipant',+ 'messageParticipants',+ 'handle role',+ { messageId: { eq: message.id } },+ ),+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ handle: RECIPIENTS.to, role: 'TO' }),+ expect.objectContaining({ handle: RECIPIENTS.cc, role: 'CC' }),+ expect.objectContaining({ handle: RECIPIENTS.bcc, role: 'BCC' }),+ ]),+ );+ }, 60000);++ it('sends a synced Gmail draft through GraphQL and replaces it in the database', async () => {+ const [draft] = await findRecordNodesByFilter<{+ id: string;+ isDraft: boolean;+ }>('message', 'messages', 'id isDraft', {+ subject: { eq: DRAFT_SUBJECT },+ });++ expect(draft).toMatchObject({+ isDraft: true,+ });+ expect(+ await findRecordNodesByFilter<{+ messageChannelId: string;+ messageExternalId: string;+ }>(+ 'messageChannelMessageAssociation',+ 'messageChannelMessageAssociations',+ 'messageChannelId messageExternalId',+ { messageId: { eq: draft.id } },+ ),+ ).toEqual([+ expect.objectContaining({+ messageChannelId: channel.channelId,+ messageExternalId: DRAFT_MESSAGE.id,+ }),+ ]);+ expect(+ await findRecordNodesByFilter<{ handle: string; role: string }>(+ 'messageParticipant',+ 'messageParticipants',+ 'handle role',+ { messageId: { eq: draft.id } },+ ),+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ handle: RECIPIENTS.to, role: 'TO' }),+ expect.objectContaining({ handle: RECIPIENTS.cc, role: 'CC' }),+ expect.objectContaining({ handle: RECIPIENTS.bcc, role: 'BCC' }),+ ]),+ );++ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ to: RECIPIENTS.to,+ cc: RECIPIENTS.cc,+ bcc: RECIPIENTS.bcc,+ subject: DRAFT_SUBJECT,+ body: 'Gmail draft body',+ draftMessageId: draft.id,+ });++ expect(result).toMatchObject({ success: true });+ const [sentMessage] = await findRecordNodesByFilter<{+ id: string;+ isDraft: boolean;+ messageThreadId: string | null;+ text: string | null;+ }>('message', 'messages', 'id isDraft messageThreadId text', {+ subject: { eq: DRAFT_SUBJECT },+ });++ expect(sentMessage).toEqual(+ expect.objectContaining({+ isDraft: false,+ messageThreadId: expect.any(String),+ text: 'Gmail draft body',+ }),+ );+ const [association] = await findRecordNodesByFilter<{+ messageChannelId: string;+ messageExternalId: string;+ }>(+ 'messageChannelMessageAssociation',+ 'messageChannelMessageAssociations',+ 'messageChannelId messageExternalId',+ { messageId: { eq: sentMessage.id } },+ );++ expect(association.messageChannelId).toBe(channel.channelId);+ expect(association.messageExternalId).not.toBe(DRAFT_MESSAGE.id);+ expect(result.messageThreadId).toEqual(expect.any(String));+ }, 60000);++ it('creates and persists a calendar event with invitations and conferencing', async () => {+ const title = `Google calendar outbound ${randomUUID()}`;++ const result = await createCalendarEvent({+ connectedAccountId: channel.connectedAccountId,+ title,+ description: 'Planning meeting',+ location: 'Room 101',+ startsAt: '2026-08-13T09:00:00Z',+ endsAt: '2026-08-13T10:00:00Z',+ timeZone: 'UTC',+ attendees: RECIPIENTS.to,+ sendInvitations: true,+ addConferencing: true,+ });++ expect(result).toMatchObject({ success: true });+ expect(result.iCalUid).toContain('@google.com');+ expect(google.createdCalendarEvents).toEqual([+ expect.objectContaining({+ summary: title,+ attendees: [expect.objectContaining({ email: RECIPIENTS.to })],+ conferenceData: expect.objectContaining({+ createRequest: expect.any(Object),+ }),+ }),+ ]);+ expect(await findImportedCalendarEventTitles([title])).toEqual([title]);+ }, 60000);+});diff --git a/packages/twenty-server/test/integration/google/mocks/google-identity-handlers.util.ts b/packages/twenty-server/test/integration/google/mocks/google-identity-handlers.util.tsindex 13c42a537f3..d1ef4f18540 100644--- a/packages/twenty-server/test/integration/google/mocks/google-identity-handlers.util.ts+++ b/packages/twenty-server/test/integration/google/mocks/google-identity-handlers.util.ts@@ -20,6 +20,9 @@ export const googleIdentityHandlers = (handle: string): MswHandler[] => [http.get('https://gmail.googleapis.com/gmail/v1/users/me/profile', () =>HttpResponse.json({ emailAddress: handle, messagesTotal: 0 }),),+ http.get('https://people.googleapis.com/v1/people/me', () =>+ HttpResponse.json({ names: [{ displayName: 'Jane Austen' }] }),+ ),http.get('*/gmail/v1/users/me/settings/sendAs', () =>HttpResponse.json({ sendAs: [{ sendAsEmail: handle, isPrimary: true }] }),),diff --git a/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts b/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.tsindex c6d26ffc69d..01c89d2deae 100644--- a/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts+++ b/packages/twenty-server/test/integration/google/mocks/setup-google-mock.util.ts@@ -24,6 +24,9 @@ const DEFAULT_LABELS: gmail_v1.Schema$Label[] = [export type GoogleMock = {labels: MockEntityStore<gmail_v1.Schema$Label>;+ sentMessages: Array<{ raw: string; threadId?: string }>;+ draftMessages: Array<{ raw: string; threadId?: string }>;+ createdCalendarEvents: calendar_v3.Schema$Event[];actAsAccount: (handle: string) => void;serveMessageList: (messages: gmail_v1.Schema$Message[]) => void;serveHistory: (addedMessages: gmail_v1.Schema$Message[]) => void;@@ -70,16 +73,76 @@ export const setupGoogleMock = ({labels?: gmail_v1.Schema$Label[];}): GoogleMock => {const labelStore = createMockEntityStore(labels, (label) => label.id ?? '');+ const sentMessages: Array<{ raw: string; threadId?: string }> = [];+ const draftMessages: Array<{ raw: string; threadId?: string }> = [];+ const createdCalendarEvents: calendar_v3.Schema$Event[] = [];const httpMock = setupHttpMock(...googleTokenHandlers(),...googleIdentityHandlers(handle),...googleCalendarEventsHandlers([], 'mock-calendar-sync-token'),...gmailMailboxHandlers(inbox, labelStore),+ http.post('*/gmail/v1/users/me/messages/send', async ({ request }) => {+ const body = (await request.json()) as { raw: string; threadId?: string };++ sentMessages.push({+ raw: Buffer.from(body.raw, 'base64url').toString(),+ threadId: body.threadId,+ });++ const id = `gmail-sent-${sentMessages.length}`;++ return HttpResponse.json({ id, threadId: body.threadId ?? id });+ }),+ http.post('*/gmail/v1/users/me/drafts', async ({ request }) => {+ const body = (await request.json()) as {+ message: { raw: string; threadId?: string };+ };++ draftMessages.push({+ raw: Buffer.from(body.message.raw, 'base64url').toString(),+ threadId: body.message.threadId,+ });++ return HttpResponse.json({ id: `gmail-draft-${draftMessages.length}` });+ }),+ http.get('*/gmail/v1/users/me/drafts', () =>+ HttpResponse.json({+ drafts: [+ {+ id: 'gmail-synced-draft',+ message: { id: 'gmail-draft-message' },+ },+ ],+ }),+ ),+ http.delete(+ '*/gmail/v1/users/me/drafts/:draftId',+ () => new HttpResponse(null, { status: 204 }),+ ),+ http.post(GOOGLE_CALENDAR_EVENTS_URL, async ({ request }) => {+ const event = (await request.json()) as calendar_v3.Schema$Event;+ const id = `google-created-calendar-event-${createdCalendarEvents.length + 1}`;+ const createdEvent = {+ ...event,+ id,+ iCalUID: `${id}@google.com`,+ status: 'confirmed',+ created: '2026-08-13T00:00:00.000Z',+ updated: '2026-08-13T00:00:00.000Z',+ };++ createdCalendarEvents.push(createdEvent);++ return HttpResponse.json(createdEvent);+ }),);return {labels: labelStore,+ sentMessages,+ draftMessages,+ createdCalendarEvents,actAsAccount: (accountHandle) =>httpMock.use(...googleIdentityHandlers(accountHandle)),serveMessageList: (messages) =>diff --git a/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.ts b/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.tsnew file mode 100644index 00000000000..6943c00a00e--- /dev/null+++ b/packages/twenty-server/test/integration/imap/suites/imap-smtp-outbound.integration-spec.ts@@ -0,0 +1,137 @@+import { randomUUID } from 'node:crypto';++import { EmailConnectionSecurity } from 'src/engine/core-modules/imap-smtp-caldav-connection/enums/email-connection-security.enum';+import { MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';+import { deleteConnectedAccount } from 'test/integration/metadata/suites/connected-account/utils/delete-connected-account.util';+import { saveImapSmtpCaldavAccount } from 'test/integration/metadata/suites/connected-account/utils/save-imap-smtp-caldav-account.util';+import { updateConfigVariable } from 'test/integration/twenty-config/utils/update-config-variable.util';+import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { getCoreRepository } from 'test/integration/utils/get-core-repository.util';+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';+import { sendEmail } from 'test/integration/utils/send-email.util';+import {+ type GreenmailServer,+ startGreenmailContainer,+} from 'test/integration/utils/start-greenmail-container.util';++const PASSWORD = 'greenmail-password';+const HANDLE = `imap-smtp-outbound-${randomUUID()}@acme.test`;++describe('IMAP/SMTP outbound messaging (integration)', () => {+ let greenmail: GreenmailServer;+ let connectedAccountId: string;+ let messageChannelId: string;++ beforeAll(async () => {+ await updateConfigVariable({+ input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: false },+ });++ greenmail = await startGreenmailContainer({+ username: HANDLE,+ password: PASSWORD,+ });++ const { data } = await saveImapSmtpCaldavAccount({+ input: {+ handle: HANDLE,+ connectionParameters: {+ IMAP: {+ host: greenmail.host,+ port: greenmail.imapPort,+ username: HANDLE.split('@')[0],+ password: PASSWORD,+ connectionSecurity: EmailConnectionSecurity.NONE,+ },+ SMTP: {+ host: greenmail.host,+ port: greenmail.smtpPort,+ username: HANDLE.split('@')[0],+ password: PASSWORD,+ connectionSecurity: EmailConnectionSecurity.NONE,+ },+ },+ },+ expectToFail: false,+ });++ connectedAccountId = data.connectedAccountId;+ messageChannelId = (+ await getCoreRepository<MessageChannelEntity>(+ MessageChannelEntity,+ ).findOneByOrFail({ connectedAccountId })+ ).id;++ await runMessageChannelSync(messageChannelId);+ }, 300000);++ afterAll(async () => {+ await updateConfigVariable({+ input: { key: 'OUTBOUND_HTTP_SAFE_MODE_ENABLED', value: true },+ }).catch(() => undefined);++ if (connectedAccountId) {+ await deleteConnectedAccount({+ id: connectedAccountId,+ expectToFail: false,+ }).catch(() => undefined);+ }++ await greenmail?.stop().catch(() => undefined);+ });++ it('sends a threaded SMTP message through GraphQL and persists it', async () => {+ const subject = `IMAP/SMTP outbound ${randomUUID()}`;++ const result = await sendEmail({+ connectedAccountId,+ to: HANDLE,+ cc: HANDLE,+ bcc: HANDLE,+ subject,+ body: '<p>SMTP reply body</p>',+ inReplyTo: '<[email protected]>',+ });++ expect(result).toMatchObject({ success: true });++ const [message] = await findRecordNodesByFilter<{+ id: string;+ isDraft: boolean;+ messageThreadId: string | null;+ text: string | null;+ }>('message', 'messages', 'id isDraft messageThreadId text', {+ subject: { eq: subject },+ });++ expect(message).toMatchObject({+ isDraft: false,+ messageThreadId: expect.any(String),+ text: 'SMTP reply body',+ });+ expect(+ await findRecordNodesByFilter<{+ messageChannelId: string;+ }>(+ 'messageChannelMessageAssociation',+ 'messageChannelMessageAssociations',+ 'messageChannelId',+ { messageId: { eq: message.id } },+ ),+ ).toEqual([expect.objectContaining({ messageChannelId })]);+ expect(+ await findRecordNodesByFilter<{ handle: string; role: string }>(+ 'messageParticipant',+ 'messageParticipants',+ 'handle role',+ { messageId: { eq: message.id } },+ ),+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ handle: HANDLE, role: 'TO' }),+ expect.objectContaining({ handle: HANDLE, role: 'CC' }),+ expect.objectContaining({ handle: HANDLE, role: 'BCC' }),+ ]),+ );+ }, 300000);+});diff --git a/packages/twenty-server/test/integration/microsoft/messaging/outbound.integration-spec.ts b/packages/twenty-server/test/integration/microsoft/messaging/outbound.integration-spec.tsnew file mode 100644index 00000000000..d4e38d82607--- /dev/null+++ b/packages/twenty-server/test/integration/microsoft/messaging/outbound.integration-spec.ts@@ -0,0 +1,265 @@+import { randomUUID } from 'node:crypto';++import { ConnectedAccountProvider } from 'twenty-shared/types';++import { setupMicrosoftMock } from 'test/integration/microsoft/mocks/setup-microsoft-mock.util';+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';+import { createCalendarEvent } from 'test/integration/utils/create-calendar-event.util';+import { findImportedCalendarEventTitles } from 'test/integration/utils/find-imported-records.util';+import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { runMessageChannelSync } from 'test/integration/utils/run-message-channel-sync.util';+import { sendEmail } from 'test/integration/utils/send-email.util';++const HANDLE = '[email protected]';+const RECIPIENTS = {+ to: '[email protected]',+ cc: '[email protected]',+ bcc: '[email protected]',+};+const DRAFT_SUBJECT = `Microsoft draft ${randomUUID()}`;+const DRAFT_MESSAGE = {+ id: 'microsoft-draft-message',+ subject: DRAFT_SUBJECT,+ body: { contentType: 'text', content: 'Microsoft draft body' },+ receivedDateTime: '2026-08-13T00:00:00.000Z',+ internetMessageId: '<[email protected]>',+ conversationId: 'microsoft-draft-conversation',+ parentFolderId: 'drafts',+ isDraft: true,+ from: { emailAddress: { address: HANDLE } },+ toRecipients: [{ emailAddress: { address: RECIPIENTS.to } }],+ ccRecipients: [{ emailAddress: { address: RECIPIENTS.cc } }],+ bccRecipients: [{ emailAddress: { address: RECIPIENTS.bcc } }],+};++describe('Microsoft outbound messaging and calendar creation (integration)', () => {+ const microsoft = setupMicrosoftMock({+ handle: HANDLE,+ folders: [+ { id: 'inbox', displayName: 'Inbox' },+ { id: 'sentitems', displayName: 'Sent Items' },+ { id: 'drafts', displayName: 'Drafts' },+ ],+ messages: [DRAFT_MESSAGE],+ });++ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;++ beforeAll(async () => {+ channel = await connectMessagingAccount({+ provider: ConnectedAccountProvider.MICROSOFT,+ handle: HANDLE,+ });+ await runMessageChannelSync(channel.channelId);+ }, 60000);++ beforeEach(() => {+ microsoft.createdMessages.length = 0;+ microsoft.patchedMessages.length = 0;+ microsoft.sentMessageIds.length = 0;+ microsoft.createdCalendarEvents.length = 0;+ });++ afterAll(async () => {+ await channel?.cleanup().catch(() => undefined);+ });++ it('sends a reply through Graph with To, CC, and BCC recipients', async () => {+ const subject = `Microsoft outbound ${randomUUID()}`;++ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ to: RECIPIENTS.to,+ cc: RECIPIENTS.cc,+ bcc: RECIPIENTS.bcc,+ subject,+ body: '<p>Microsoft reply body</p>',+ inReplyTo: '<[email protected]>',+ });++ expect(result).toMatchObject({ success: true });+ expect(microsoft.patchedMessages).toEqual([+ expect.objectContaining({+ subject,+ toRecipients: [{ emailAddress: { address: RECIPIENTS.to } }],+ ccRecipients: [{ emailAddress: { address: RECIPIENTS.cc } }],+ bccRecipients: [{ emailAddress: { address: RECIPIENTS.bcc } }],+ }),+ ]);+ expect(microsoft.sentMessageIds).toEqual(['microsoft-reply-message']);+ const [message] = await findRecordNodesByFilter<{+ id: string;+ isDraft: boolean;+ messageThreadId: string | null;+ text: string | null;+ }>('message', 'messages', 'id isDraft messageThreadId text', {+ subject: { eq: subject },+ });++ expect(message).toMatchObject({+ isDraft: false,+ messageThreadId: expect.any(String),+ text: 'Microsoft reply body',+ });+ expect(+ await findRecordNodesByFilter<{+ messageChannelId: string;+ messageExternalId: string;+ }>(+ 'messageChannelMessageAssociation',+ 'messageChannelMessageAssociations',+ 'messageChannelId messageExternalId',+ { messageId: { eq: message.id } },+ ),+ ).toEqual([+ expect.objectContaining({+ messageChannelId: channel.channelId,+ messageExternalId: 'microsoft-reply-message',+ }),+ ]);+ expect(+ await findRecordNodesByFilter<{ handle: string; role: string }>(+ 'messageParticipant',+ 'messageParticipants',+ 'handle role',+ { messageId: { eq: message.id } },+ ),+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ handle: RECIPIENTS.to, role: 'TO' }),+ expect.objectContaining({ handle: RECIPIENTS.cc, role: 'CC' }),+ expect.objectContaining({ handle: RECIPIENTS.bcc, role: 'BCC' }),+ ]),+ );+ }, 60000);++ it('sends a synced Microsoft draft through GraphQL and replaces it in the database', async () => {+ const [draft] = await findRecordNodesByFilter<{+ id: string;+ isDraft: boolean;+ }>('message', 'messages', 'id isDraft', {+ subject: { eq: DRAFT_SUBJECT },+ });++ expect(draft).toMatchObject({+ isDraft: true,+ });+ expect(+ await findRecordNodesByFilter<{+ messageChannelId: string;+ messageExternalId: string;+ }>(+ 'messageChannelMessageAssociation',+ 'messageChannelMessageAssociations',+ 'messageChannelId messageExternalId',+ { messageId: { eq: draft.id } },+ ),+ ).toEqual([+ expect.objectContaining({+ messageChannelId: channel.channelId,+ messageExternalId: DRAFT_MESSAGE.id,+ }),+ ]);+ expect(+ await findRecordNodesByFilter<{ handle: string; role: string }>(+ 'messageParticipant',+ 'messageParticipants',+ 'handle role',+ { messageId: { eq: draft.id } },+ ),+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ handle: RECIPIENTS.to, role: 'TO' }),+ expect.objectContaining({ handle: RECIPIENTS.cc, role: 'CC' }),+ expect.objectContaining({ handle: RECIPIENTS.bcc, role: 'BCC' }),+ ]),+ );++ const result = await sendEmail({+ connectedAccountId: channel.connectedAccountId,+ to: RECIPIENTS.to,+ cc: RECIPIENTS.cc,+ bcc: RECIPIENTS.bcc,+ subject: DRAFT_SUBJECT,+ body: 'Microsoft draft body',+ draftMessageId: draft.id,+ });++ expect(result).toMatchObject({ success: true });+ expect(microsoft.createdMessages).toEqual([+ expect.objectContaining({+ subject: DRAFT_SUBJECT,+ toRecipients: [{ emailAddress: { address: RECIPIENTS.to } }],+ ccRecipients: [{ emailAddress: { address: RECIPIENTS.cc } }],+ bccRecipients: [{ emailAddress: { address: RECIPIENTS.bcc } }],+ }),+ ]);+ expect(microsoft.sentMessageIds).toEqual(['microsoft-message-1']);+ const [sentMessage] = await findRecordNodesByFilter<{+ id: string;+ isDraft: boolean;+ messageThreadId: string | null;+ text: string | null;+ }>('message', 'messages', 'id isDraft messageThreadId text', {+ subject: { eq: DRAFT_SUBJECT },+ });++ expect(sentMessage).toMatchObject({+ isDraft: false,+ messageThreadId: expect.any(String),+ text: 'Microsoft draft body',+ });+ expect(+ await findRecordNodesByFilter<{+ messageChannelId: string;+ messageExternalId: string;+ }>(+ 'messageChannelMessageAssociation',+ 'messageChannelMessageAssociations',+ 'messageChannelId messageExternalId',+ { messageId: { eq: sentMessage.id } },+ ),+ ).toEqual([+ expect.objectContaining({+ messageChannelId: channel.channelId,+ messageExternalId: 'microsoft-message-1',+ }),+ ]);+ expect(result.messageThreadId).toEqual(expect.any(String));+ }, 60000);++ it('creates and persists a calendar event with invitations and conferencing', async () => {+ const title = `Microsoft calendar outbound ${randomUUID()}`;++ const result = await createCalendarEvent({+ connectedAccountId: channel.connectedAccountId,+ title,+ description: 'Planning meeting',+ location: 'Room 101',+ startsAt: '2026-08-13T09:00:00Z',+ endsAt: '2026-08-13T10:00:00Z',+ timeZone: 'UTC',+ attendees: RECIPIENTS.to,+ sendInvitations: true,+ addConferencing: true,+ });++ expect(result).toMatchObject({ success: true });+ expect(result.iCalUid).toContain('@microsoft.com');+ expect(microsoft.createdCalendarEvents).toEqual([+ expect.objectContaining({+ subject: title,+ location: { displayName: 'Room 101' },+ attendees: [+ {+ emailAddress: { address: RECIPIENTS.to },+ type: 'required',+ },+ ],+ isOnlineMeeting: true,+ onlineMeetingProvider: 'teamsForBusiness',+ }),+ ]);+ expect(await findImportedCalendarEventTitles([title])).toEqual([title]);+ }, 60000);+});diff --git a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.tsindex b170f471c30..32024726adc 100644--- a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts+++ b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-auth-handlers.util.ts@@ -9,7 +9,8 @@ export const microsoftAuthHandlers = (handle: string): MswHandler[] => [access_token: 'mock-access-token',refresh_token: 'mock-refresh-token',expires_in: 3600,- scope: 'openid profile email offline_access',+ scope:+ 'openid profile email offline_access Mail.Send Calendars.ReadWrite',}),),http.get('https://graph.microsoft.com/v1.0/me', () =>diff --git a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-mailbox-handlers.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-mailbox-handlers.util.tsindex 7e916d66054..357e3f4ea65 100644--- a/packages/twenty-server/test/integration/microsoft/mocks/microsoft-mailbox-handlers.util.ts+++ b/packages/twenty-server/test/integration/microsoft/mocks/microsoft-mailbox-handlers.util.ts@@ -1,11 +1,13 @@import { type MailFolder } from '@microsoft/microsoft-graph-types';import { http, HttpResponse } from 'msw';+import { isDefined } from 'twenty-shared/utils';import { type MswHandler } from 'test/integration/utils/http-mock.util';import { type MockEntityStore } from 'test/integration/utils/mock-entity-store.util';export const microsoftMailboxHandlers = (folderStore: MockEntityStore<MailFolder>,+ messages: Array<Record<string, unknown>> = [],): MswHandler[] => [http.get('*/me/mailFolders', () =>HttpResponse.json<{ value: MailFolder[] }>({ value: folderStore.list() }),@@ -17,7 +19,37 @@ export const microsoftMailboxHandlers = ('https://graph.microsoft.com/beta/me/mailfolders/inbox/messages/delta?$deltatoken=mock-delta-token',}),),- http.post('*/$batch', () =>- HttpResponse.json<{ responses: never[] }>({ responses: [] }),- ),+ http.post('*/$batch', async ({ request }) => {+ const { requests } = (await request.json()) as {+ requests: Array<{ id: string; url: string }>;+ };++ return HttpResponse.json({+ responses: requests.map(({ id, url }) => {+ if (url.includes('/messages/delta')) {+ const folderId = url.match(/mailfolders\/([^/]+)\//)?.[1];++ return {+ id,+ status: 200,+ body: {+ value: messages+ .filter((message) => message.parentFolderId === folderId)+ .map((message) => ({ id: message.id })),+ '@odata.deltaLink': `https://graph.microsoft.com/beta${url}`,+ },+ };+ }++ const messageId = url.match(/\/me\/messages\/([^?]+)/)?.[1];+ const message = messages.find(+ (candidate) => candidate.id === messageId,+ );++ return isDefined(message)+ ? { id, status: 200, body: message }+ : { id, status: 404, body: { error: { message: 'Not Found' } } };+ }),+ });+ }),];diff --git a/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts b/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.tsindex d87d1cbfd3c..143834bd6b0 100644--- a/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts+++ b/packages/twenty-server/test/integration/microsoft/mocks/setup-microsoft-mock.util.ts@@ -23,6 +23,10 @@ const DEFAULT_FOLDERS: MailFolder[] = [export type MicrosoftMock = {folders: MockEntityStore<MailFolder>;subscriptions: MicrosoftSubscriptionStore;+ createdMessages: Array<Record<string, unknown>>;+ patchedMessages: Array<Record<string, unknown>>;+ sentMessageIds: string[];+ createdCalendarEvents: Event[];serveCalendarEvents: (events: Event[],options?: { deltaToken?: string },@@ -48,9 +52,11 @@ const microsoftGraphErrorResponse = ({export const setupMicrosoftMock = ({handle,folders = DEFAULT_FOLDERS,+ messages = [],}: {handle: string;folders?: MailFolder[];+ messages?: Array<Record<string, unknown>>;}): MicrosoftMock => {const folderStore = createMockEntityStore(folders,@@ -58,16 +64,88 @@ export const setupMicrosoftMock = ({);const subscriptionStore = createMicrosoftSubscriptionStore();+ const createdMessages: Array<Record<string, unknown>> = [];+ const patchedMessages: Array<Record<string, unknown>> = [];+ const sentMessageIds: string[] = [];+ const createdCalendarEvents: Event[] = [];const httpMock = setupHttpMock(...microsoftAuthHandlers(handle),- ...microsoftMailboxHandlers(folderStore),+ ...microsoftMailboxHandlers(folderStore, messages),...microsoftWebhookSubscriptionHandlers(subscriptionStore),+ http.post('*/me/messages', async ({ request }) => {+ const message = (await request.json()) as Record<string, unknown>;+ const id = `microsoft-message-${createdMessages.length + 1}`;++ createdMessages.push(message);++ return HttpResponse.json({+ id,+ internetMessageId: `<${id}@example.com>`,+ conversationId: `microsoft-conversation-${createdMessages.length}`,+ });+ }),+ http.post('*/me/messages/:messageId/send', ({ params }) => {+ sentMessageIds.push(params.messageId as string);++ return new HttpResponse(null, { status: 202 });+ }),+ http.delete(+ '*/me/messages/:messageId',+ () => new HttpResponse(null, { status: 204 }),+ ),+ http.get('*/me/messages', () =>+ HttpResponse.json({+ value: [+ {+ id: 'microsoft-parent-message',+ internetMessageId: '<[email protected]>',+ },+ ],+ }),+ ),+ http.post('*/me/messages/:messageId/createReply', () =>+ HttpResponse.json({+ id: 'microsoft-reply-message',+ internetMessageId: '<[email protected]>',+ conversationId: 'microsoft-parent-conversation',+ }),+ ),+ http.patch('*/me/messages/:messageId', async ({ request }) => {+ const message = (await request.json()) as Record<string, unknown>;++ patchedMessages.push(message);++ return HttpResponse.json({+ internetMessageId: '<[email protected]>',+ conversationId: 'microsoft-parent-conversation',+ });+ }),+ http.post('*/me/calendar/events', async ({ request }) => {+ const event = (await request.json()) as Event;+ const id = `microsoft-created-calendar-event-${createdCalendarEvents.length + 1}`;+ const createdEvent: Event = {+ ...event,+ id,+ iCalUId: `${id}@microsoft.com`,+ isCancelled: false,+ createdDateTime: '2026-08-13T00:00:00.000Z',+ lastModifiedDateTime: '2026-08-13T00:00:00.000Z',+ };++ createdCalendarEvents.push(createdEvent);++ return HttpResponse.json(createdEvent);+ }),);return {folders: folderStore,subscriptions: subscriptionStore,+ createdMessages,+ patchedMessages,+ sentMessageIds,+ createdCalendarEvents,serveCalendarEvents: (events,{ deltaToken = 'mock-calendar-delta-token' } = {},diff --git a/packages/twenty-server/test/integration/utils/create-calendar-event.util.ts b/packages/twenty-server/test/integration/utils/create-calendar-event.util.tsnew file mode 100644index 00000000000..26c1a74cd24--- /dev/null+++ b/packages/twenty-server/test/integration/utils/create-calendar-event.util.ts@@ -0,0 +1,50 @@+import gql from 'graphql-tag';++import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';++type CreateCalendarEventInput = {+ connectedAccountId: string;+ title: string;+ description?: string;+ location?: string;+ startsAt: string;+ endsAt: string;+ isFullDay?: boolean;+ timeZone?: string;+ attendees?: string;+ sendInvitations?: boolean;+ addConferencing?: boolean;+};++type CreateCalendarEventResult = {+ success: boolean;+ error?: string;+ iCalUid?: string;+ conferenceLink?: string;+};++const CREATE_CALENDAR_EVENT_MUTATION = gql`+ mutation CreateCalendarEventForIntegrationTest(+ $input: CreateCalendarEventInput!+ ) {+ createCalendarEvent(input: $input) {+ success+ error+ iCalUid+ conferenceLink+ }+ }+`;++export const createCalendarEvent = async (+ input: CreateCalendarEventInput,+): Promise<CreateCalendarEventResult> => {+ const response = await makeMetadataAPIRequest({+ query: CREATE_CALENDAR_EVENT_MUTATION,+ variables: { input },+ });++ expect(response.body.errors).toBeUndefined();++ return response.body.data.createCalendarEvent;+};diff --git a/packages/twenty-server/test/integration/utils/send-email.util.ts b/packages/twenty-server/test/integration/utils/send-email.util.tsnew file mode 100644index 00000000000..b70ba2a96ed--- /dev/null+++ b/packages/twenty-server/test/integration/utils/send-email.util.ts@@ -0,0 +1,43 @@+import gql from 'graphql-tag';++import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';++type SendEmailInput = {+ connectedAccountId: string;+ to: string;+ cc?: string;+ bcc?: string;+ subject: string;+ body: string;+ inReplyTo?: string;+ draftMessageId?: string;+};++type SendEmailResult = {+ success: boolean;+ error?: string;+ messageThreadId?: string;+};++const SEND_EMAIL_MUTATION = gql`+ mutation SendEmailForIntegrationTest($input: SendEmailInput!) {+ sendEmail(input: $input) {+ success+ error+ messageThreadId+ }+ }+`;++export const sendEmail = async (+ input: SendEmailInput,+): Promise<SendEmailResult> => {+ const response = await makeMetadataAPIRequest({+ query: SEND_EMAIL_MUTATION,+ variables: { input },+ });++ expect(response.body.errors).toBeUndefined();++ return response.body.data.sendEmail;+};