Skip to content

The open alternative to Salesforce, designed for AI.

fix(calendar): stop re-saving unchanged calendar events and participants on sync (#27151)

Charles Bochet9e522bb657f0
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 8cad38c98be..65b6a440d3f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -2134,6 +2134,7 @@ enum FeatureFlagKey {
IS_VALIDATION_RULES_ENABLED
IS_RECORD_LEVEL_SHARING_ENABLED
IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED
+ IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED
}
type WorkspaceUrls {
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index dafdbc49c7b..cf601932ac3 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1706,7 +1706,7 @@ export interface FeatureFlag {
__typename: 'FeatureFlag'
}
-export type FeatureFlagKey = 'IS_APPLICATION_WORKFLOWS_ENABLED' | 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' | 'IS_EXECUTION_QUOTA_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_LOGS_SETTINGS_SECTION_ENABLED' | 'IS_CONVERSATIONS_TAB_ENABLED' | 'IS_VALIDATION_RULES_ENABLED' | 'IS_RECORD_LEVEL_SHARING_ENABLED' | 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED'
+export type FeatureFlagKey = 'IS_APPLICATION_WORKFLOWS_ENABLED' | 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT' | 'IS_LOGIC_FUNCTION_PREBUILT_MODE_ENABLED' | 'IS_WORKFLOW_CORE_INDEX_PAGE_ENABLED' | 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED' | 'IS_INITIAL_OBJECT_VIEW_ENABLED' | 'IS_WEBHOOK_RATE_LIMIT_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' | 'IS_EXECUTION_QUOTA_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_LOGS_SETTINGS_SECTION_ENABLED' | 'IS_CONVERSATIONS_TAB_ENABLED' | 'IS_VALIDATION_RULES_ENABLED' | 'IS_RECORD_LEVEL_SHARING_ENABLED' | 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED' | 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED'
export interface WorkspaceUrls {
customUrl?: Scalars['String']
@@ -11410,7 +11410,8 @@ export const enumFeatureFlagKey = {
IS_CONVERSATIONS_TAB_ENABLED: 'IS_CONVERSATIONS_TAB_ENABLED' as const,
IS_VALIDATION_RULES_ENABLED: 'IS_VALIDATION_RULES_ENABLED' as const,
IS_RECORD_LEVEL_SHARING_ENABLED: 'IS_RECORD_LEVEL_SHARING_ENABLED' as const,
- IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED: 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED' as const
+ IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED: 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED' as const,
+ IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED: 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED' as const
}
export const enumIdentityProviderType = {
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index 1b5a822fb43..d810c60cc61 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -478,6 +478,7 @@ export enum FeatureFlagKey {
IS_AI_CHAT_SHARING_DROPDOWN_ENABLED = 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED',
IS_APPLICATION_WORKFLOWS_ENABLED = 'IS_APPLICATION_WORKFLOWS_ENABLED',
IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',
+ IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED = 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED',
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED = 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED',
IS_CONVERSATIONS_TAB_ENABLED = 'IS_CONVERSATIONS_TAB_ENABLED',
IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED = 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED',
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index af9536db3fe..161a35c3fa2 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -2146,6 +2146,7 @@ export enum FeatureFlagKey {
IS_AI_CHAT_SHARING_DROPDOWN_ENABLED = 'IS_AI_CHAT_SHARING_DROPDOWN_ENABLED',
IS_APPLICATION_WORKFLOWS_ENABLED = 'IS_APPLICATION_WORKFLOWS_ENABLED',
IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',
+ IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED = 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED',
IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED = 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED',
IS_CONVERSATIONS_TAB_ENABLED = 'IS_CONVERSATIONS_TAB_ENABLED',
IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED = 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED',
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
index fba2f045b58..4e65966eea4 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminFeatureFlagMetadata.ts
@@ -82,4 +82,8 @@ export const SETTINGS_ADMIN_FEATURE_FLAG_METADATA: Partial<
label: msg`Workflow chat messages`,
description: msg`Add a workflow step that posts a message in a member's AI chat.`,
},
+ [FeatureFlagKey.IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED]: {
+ label: msg`Skip unchanged calendar records`,
+ description: msg`Only write calendar events and participants that changed since the last sync.`,
+ },
};
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
index d121a80e16b..91ebc3765a2 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util.ts
@@ -14,6 +14,7 @@ const DEFAULT_SEEDED_FEATURE_FLAGS: Partial<Record<FeatureFlagKey, boolean>> = {
[FeatureFlagKey.IS_VALIDATION_RULES_ENABLED]: true,
[FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED]: false,
[FeatureFlagKey.IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED]: true,
+ [FeatureFlagKey.IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED]: true,
};
type SeedFeatureFlagsArgs = {
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts
index da36140b738..cbada2e0897 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/services/calendar-save-events.service.ts
@@ -1,7 +1,9 @@
import { Injectable } from '@nestjs/common';
+import { FeatureFlagKey } from 'twenty-shared/types';
import { Any } from 'typeorm';
+import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { type CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
@@ -18,6 +20,7 @@ export class CalendarSaveEventsService {
constructor(
private readonly workspaceOrmManager: WorkspaceOrmManager,
private readonly calendarEventParticipantService: CalendarEventParticipantService,
+ private readonly featureFlagService: FeatureFlagService,
) {}
public async saveCalendarEventsAndEnqueueContactCreationJob(
@@ -28,6 +31,12 @@ export class CalendarSaveEventsService {
): Promise<{ calendarEventIds: string[] }> {
const authContext = buildSystemAuthContext(workspaceId);
+ const shouldSkipUnchangedRecords =
+ await this.featureFlagService.isFeatureEnabled(
+ FeatureFlagKey.IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED,
+ workspaceId,
+ );
+
const { savedParticipantIds, calendarEventIds } =
await this.workspaceOrmManager.executeInWorkspaceContext(
async () => {
@@ -47,13 +56,33 @@ export class CalendarSaveEventsService {
},
});
+ const calendarEventRepository =
+ this.workspaceOrmManager.getRepository<CalendarEventWorkspaceEntity>(
+ 'calendarEvent',
+ { shouldBypassPermissionChecks: true },
+ );
+
+ const existingCalendarEvents = shouldSkipUnchangedRecords
+ ? await calendarEventRepository.find({
+ where: {
+ id: Any(
+ existingAssociations.map(
+ (association) => association.calendarEventId,
+ ),
+ ),
+ },
+ })
+ : [];
+
const {
saveOperations,
+ existingCalendarEventIds,
participantsOfNewEvents,
participantsOfExistingEvents,
} = buildCalendarEventSaveOperations({
fetchedCalendarEvents,
existingAssociations,
+ existingCalendarEvents,
calendarChannelId: calendarChannel.id,
});
@@ -73,6 +102,7 @@ export class CalendarSaveEventsService {
...participantsOfExistingEvents,
],
existingParticipants,
+ shouldSkipUnchangedParticipants: shouldSkipUnchangedRecords,
});
await this.workspaceOrmManager.runInWorkspaceTransaction(
@@ -130,9 +160,7 @@ export class CalendarSaveEventsService {
...saveOperations.associationsToInsert.map(
({ calendarEventId }) => calendarEventId,
),
- ...saveOperations.calendarEventsToUpdate.map(
- ({ criteria }) => criteria,
- ),
+ ...existingCalendarEventIds,
],
};
},
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-save-plan.type.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-save-plan.type.ts
index eaf2764587b..b91a629c47e 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-save-plan.type.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-save-plan.type.ts
@@ -3,6 +3,7 @@ import { type FetchedParticipantWithCalendarEventId } from 'src/modules/calendar
export type CalendarEventSavePlan = {
saveOperations: CalendarEventSaveOperations;
+ existingCalendarEventIds: string[];
participantsOfNewEvents: FetchedParticipantWithCalendarEventId[];
participantsOfExistingEvents: FetchedParticipantWithCalendarEventId[];
};
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/build-calendar-event-save-operations.util.spec.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/build-calendar-event-save-operations.util.spec.ts
new file mode 100644
index 00000000000..6a9113dbf89
--- /dev/null
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/build-calendar-event-save-operations.util.spec.ts
@@ -0,0 +1,261 @@
+import { buildCalendarEventSaveOperations } from 'src/modules/calendar/calendar-event-import-manager/utils/build-calendar-event-save-operations.util';
+import { type ComparableCalendarEvent } from 'src/modules/calendar/calendar-event-import-manager/utils/has-calendar-event-changed.util';
+import { type CalendarChannelEventAssociationWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-channel-event-association.workspace-entity';
+import { type FetchedCalendarEvent } from 'src/modules/calendar/common/types/fetched-calendar-event.type';
+
+const CALENDAR_CHANNEL_ID = 'calendar-channel-id';
+const CALENDAR_EVENT_ID = 'calendar-event-id';
+const ASSOCIATION_ID = 'association-id';
+
+const buildFetchedCalendarEvent = (
+ overrides: Partial<FetchedCalendarEvent> = {},
+): FetchedCalendarEvent => ({
+ id: 'external-event-id',
+ title: 'Weekly sync',
+ iCalUid: 'ical-uid',
+ description: 'Agenda',
+ startsAt: '2026-10-02T10:00:00+02:00',
+ endsAt: '2026-10-02T11:00:00+02:00',
+ location: '',
+ isFullDay: false,
+ isCanceled: false,
+ conferenceLinkLabel: 'Meet',
+ conferenceLinkUrl: 'https://meet.example.com/abc',
+ externalCreatedAt: '2026-09-01T08:00:00.000Z',
+ externalUpdatedAt: '2026-09-15T08:00:00.000Z',
+ conferenceSolution: 'hangoutsMeet',
+ participants: [
+ {
+ handle: '[email protected]',
+ displayName: 'John Doe',
+ responseStatus: 'ACCEPTED',
+ isOrganizer: true,
+ },
+ ],
+ status: 'confirmed',
+ ...overrides,
+});
+
+const buildExistingCalendarEvent = (
+ overrides: Partial<ComparableCalendarEvent> = {},
+): ComparableCalendarEvent => ({
+ id: CALENDAR_EVENT_ID,
+ title: 'Weekly sync',
+ iCalUid: 'ical-uid',
+ description: 'Agenda',
+ startsAt: '2026-10-02T08:00:00.000Z',
+ endsAt: '2026-10-02T09:00:00.000Z',
+ location: null,
+ isFullDay: false,
+ isCanceled: false,
+ conferenceSolution: 'hangoutsMeet',
+ conferenceLink: {
+ primaryLinkLabel: 'Meet',
+ primaryLinkUrl: 'https://meet.example.com/abc',
+ secondaryLinks: null,
+ },
+ ...overrides,
+});
+
+const buildExistingAssociation = (
+ overrides: Partial<CalendarChannelEventAssociationWorkspaceEntity> = {},
+): CalendarChannelEventAssociationWorkspaceEntity =>
+ ({
+ id: ASSOCIATION_ID,
+ calendarEventId: CALENDAR_EVENT_ID,
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ eventExternalId: 'external-event-id',
+ recurringEventExternalId: '',
+ ...overrides,
+ }) as CalendarChannelEventAssociationWorkspaceEntity;
+
+describe('buildCalendarEventSaveOperations', () => {
+ it('skips updates for an existing event that did not change', () => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [buildFetchedCalendarEvent()],
+ existingAssociations: [buildExistingAssociation()],
+ existingCalendarEvents: [buildExistingCalendarEvent()],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations).toEqual({
+ calendarEventsToInsert: [],
+ calendarEventsToUpdate: [],
+ associationsToInsert: [],
+ associationsToUpdate: [],
+ });
+ expect(plan.existingCalendarEventIds).toEqual([CALENDAR_EVENT_ID]);
+ expect(plan.participantsOfExistingEvents).toEqual([
+ {
+ handle: '[email protected]',
+ displayName: 'John Doe',
+ responseStatus: 'ACCEPTED',
+ isOrganizer: true,
+ calendarEventId: CALENDAR_EVENT_ID,
+ },
+ ]);
+ });
+
+ it('ignores provider bookkeeping timestamps when nothing else changed', () => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [
+ buildFetchedCalendarEvent({
+ externalCreatedAt: '2026-10-02T15:00:00.000Z',
+ externalUpdatedAt: '2026-10-02T15:00:00.000Z',
+ }),
+ ],
+ existingAssociations: [buildExistingAssociation()],
+ existingCalendarEvents: [buildExistingCalendarEvent()],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations.calendarEventsToUpdate).toEqual([]);
+ });
+
+ it('reads timestamps without an offset as UTC like the database does', () => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [
+ buildFetchedCalendarEvent({
+ startsAt: '2026-10-02T08:00:00.0000000',
+ endsAt: '2026-10-02T09:00:00.0000000',
+ }),
+ ],
+ existingAssociations: [buildExistingAssociation()],
+ existingCalendarEvents: [buildExistingCalendarEvent()],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations.calendarEventsToUpdate).toEqual([]);
+ });
+
+ it('treats an empty fetched end date as equal to a null persisted one', () => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [buildFetchedCalendarEvent({ endsAt: '' })],
+ existingAssociations: [buildExistingAssociation()],
+ existingCalendarEvents: [buildExistingCalendarEvent({ endsAt: null })],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations.calendarEventsToUpdate).toEqual([]);
+ });
+
+ it.each<[string, Partial<FetchedCalendarEvent>, Record<string, unknown>]>([
+ [
+ 'title',
+ { title: 'Weekly sync (moved)' },
+ { title: 'Weekly sync (moved)' },
+ ],
+ [
+ 'startsAt',
+ { startsAt: '2026-10-02T10:30:00+02:00' },
+ { startsAt: '2026-10-02T10:30:00+02:00' },
+ ],
+ ['isCanceled', { isCanceled: true }, { isCanceled: true }],
+ [
+ 'conference link',
+ { conferenceLinkUrl: 'https://meet.example.com/xyz' },
+ {
+ conferenceLink: {
+ primaryLinkLabel: 'Meet',
+ primaryLinkUrl: 'https://meet.example.com/xyz',
+ secondaryLinks: [],
+ },
+ },
+ ],
+ ['location', { location: 'Room 1' }, { location: 'Room 1' }],
+ ])(
+ 'updates an existing event when its %s changed',
+ (_, overrides, written) => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [buildFetchedCalendarEvent(overrides)],
+ existingAssociations: [buildExistingAssociation()],
+ existingCalendarEvents: [buildExistingCalendarEvent()],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations.calendarEventsToUpdate).toEqual([
+ {
+ criteria: CALENDAR_EVENT_ID,
+ partialEntity: expect.objectContaining(written),
+ },
+ ]);
+ expect(plan.saveOperations.associationsToUpdate).toEqual([]);
+ },
+ );
+
+ it('updates an existing event that has secondary links to clear them', () => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [buildFetchedCalendarEvent()],
+ existingAssociations: [buildExistingAssociation()],
+ existingCalendarEvents: [
+ buildExistingCalendarEvent({
+ conferenceLink: {
+ primaryLinkLabel: 'Meet',
+ primaryLinkUrl: 'https://meet.example.com/abc',
+ secondaryLinks: [{ url: 'https://example.com', label: '' }],
+ },
+ }),
+ ],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations.calendarEventsToUpdate).toHaveLength(1);
+ });
+
+ it('updates the event and its association when the event was not loaded', () => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [buildFetchedCalendarEvent()],
+ existingAssociations: [buildExistingAssociation()],
+ existingCalendarEvents: [],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations.calendarEventsToUpdate).toHaveLength(1);
+ expect(plan.saveOperations.associationsToUpdate).toEqual([
+ {
+ criteria: ASSOCIATION_ID,
+ partialEntity: { recurringEventExternalId: '' },
+ },
+ ]);
+ });
+
+ it('updates the association only when the recurring event id changed', () => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [
+ buildFetchedCalendarEvent({ recurringEventExternalId: 'recurring-id' }),
+ ],
+ existingAssociations: [buildExistingAssociation()],
+ existingCalendarEvents: [buildExistingCalendarEvent()],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations.calendarEventsToUpdate).toEqual([]);
+ expect(plan.saveOperations.associationsToUpdate).toEqual([
+ {
+ criteria: ASSOCIATION_ID,
+ partialEntity: { recurringEventExternalId: 'recurring-id' },
+ },
+ ]);
+ });
+
+ it('inserts events that have no existing association', () => {
+ const plan = buildCalendarEventSaveOperations({
+ fetchedCalendarEvents: [buildFetchedCalendarEvent()],
+ existingAssociations: [],
+ existingCalendarEvents: [],
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ });
+
+ expect(plan.saveOperations.calendarEventsToInsert).toHaveLength(1);
+ expect(plan.saveOperations.associationsToInsert).toEqual([
+ {
+ calendarEventId: plan.saveOperations.calendarEventsToInsert[0].id,
+ eventExternalId: 'external-event-id',
+ calendarChannelId: CALENDAR_CHANNEL_ID,
+ recurringEventExternalId: '',
+ },
+ ]);
+ expect(plan.existingCalendarEventIds).toEqual([]);
+ expect(plan.participantsOfNewEvents).toHaveLength(1);
+ });
+});
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/build-calendar-event-save-operations.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/build-calendar-event-save-operations.util.ts
index d442a72f0da..d9e71c9641b 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/build-calendar-event-save-operations.util.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/build-calendar-event-save-operations.util.ts
@@ -3,6 +3,10 @@ import { v4 as uuid } from 'uuid';
import { type CalendarEventSaveOperations } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-save-operations.type';
import { type CalendarEventSavePlan } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-save-plan.type';
+import {
+ type ComparableCalendarEvent,
+ hasCalendarEventChanged,
+} from 'src/modules/calendar/calendar-event-import-manager/utils/has-calendar-event-changed.util';
import { type CalendarChannelEventAssociationWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-channel-event-association.workspace-entity';
import { type FetchedCalendarEvent } from 'src/modules/calendar/common/types/fetched-calendar-event.type';
import { type FetchedParticipantWithCalendarEventId } from 'src/modules/calendar/common/types/fetched-participant-with-calendar-event-id.type';
@@ -10,10 +14,12 @@ import { type FetchedParticipantWithCalendarEventId } from 'src/modules/calendar
export const buildCalendarEventSaveOperations = ({
fetchedCalendarEvents,
existingAssociations,
+ existingCalendarEvents,
calendarChannelId,
}: {
fetchedCalendarEvents: FetchedCalendarEvent[];
existingAssociations: CalendarChannelEventAssociationWorkspaceEntity[];
+ existingCalendarEvents: ComparableCalendarEvent[];
calendarChannelId: string;
}): CalendarEventSavePlan => {
const existingAssociationByEventExternalId = new Map(
@@ -22,6 +28,12 @@ export const buildCalendarEventSaveOperations = ({
association,
]),
);
+ const existingCalendarEventById = new Map(
+ existingCalendarEvents.map((calendarEvent) => [
+ calendarEvent.id,
+ calendarEvent,
+ ]),
+ );
const saveOperations: CalendarEventSaveOperations = {
calendarEventsToInsert: [],
@@ -29,6 +41,7 @@ export const buildCalendarEventSaveOperations = ({
associationsToInsert: [],
associationsToUpdate: [],
};
+ const existingCalendarEventIds: string[] = [];
const participantsOfNewEvents: FetchedParticipantWithCalendarEventId[] = [];
const participantsOfExistingEvents: FetchedParticipantWithCalendarEventId[] =
[];
@@ -64,15 +77,32 @@ export const buildCalendarEventSaveOperations = ({
if (isDefined(existingAssociation)) {
const { calendarEventId } = existingAssociation;
+ const existingCalendarEvent =
+ existingCalendarEventById.get(calendarEventId);
+
+ existingCalendarEventIds.push(calendarEventId);
+
+ if (
+ !isDefined(existingCalendarEvent) ||
+ hasCalendarEventChanged({ existingCalendarEvent, calendarEvent })
+ ) {
+ saveOperations.calendarEventsToUpdate.push({
+ criteria: calendarEventId,
+ partialEntity: calendarEvent,
+ });
+ }
+
+ if (
+ !isDefined(existingCalendarEvent) ||
+ (existingAssociation.recurringEventExternalId ?? '') !==
+ recurringEventExternalId
+ ) {
+ saveOperations.associationsToUpdate.push({
+ criteria: existingAssociation.id,
+ partialEntity: { recurringEventExternalId },
+ });
+ }
- saveOperations.calendarEventsToUpdate.push({
- criteria: calendarEventId,
- partialEntity: calendarEvent,
- });
- saveOperations.associationsToUpdate.push({
- criteria: existingAssociation.id,
- partialEntity: { recurringEventExternalId },
- });
participantsOfExistingEvents.push(
...participants.map((participant) => ({
...participant,
@@ -105,6 +135,7 @@ export const buildCalendarEventSaveOperations = ({
return {
saveOperations,
+ existingCalendarEventIds,
participantsOfNewEvents,
participantsOfExistingEvents,
};
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/has-calendar-event-changed.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/has-calendar-event-changed.util.ts
new file mode 100644
index 00000000000..3bea47f42a5
--- /dev/null
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/has-calendar-event-changed.util.ts
@@ -0,0 +1,74 @@
+import { isNonEmptyString } from '@sniptt/guards';
+import { isNonEmptyArray, parseToInstantOrThrow } from 'twenty-shared/utils';
+
+import { type CalendarEventWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event.workspace-entity';
+
+export type ComparableCalendarEvent = Pick<
+ CalendarEventWorkspaceEntity,
+ | 'id'
+ | 'iCalUid'
+ | 'title'
+ | 'description'
+ | 'startsAt'
+ | 'endsAt'
+ | 'location'
+ | 'isFullDay'
+ | 'isCanceled'
+ | 'conferenceSolution'
+ | 'conferenceLink'
+>;
+
+const TEXT_FIELD_NAMES = [
+ 'iCalUid',
+ 'title',
+ 'description',
+ 'location',
+ 'conferenceSolution',
+] as const;
+
+const DATE_TIME_FIELD_NAMES = ['startsAt', 'endsAt'] as const;
+
+const BOOLEAN_FIELD_NAMES = ['isFullDay', 'isCanceled'] as const;
+
+const toEpochMilliseconds = (value: string | Date | null): number | null => {
+ if (value instanceof Date) {
+ return value.getTime();
+ }
+
+ if (!isNonEmptyString(value)) {
+ return null;
+ }
+
+ try {
+ return parseToInstantOrThrow(value).epochMilliseconds;
+ } catch {
+ return Number.NaN;
+ }
+};
+
+export const hasCalendarEventChanged = ({
+ existingCalendarEvent,
+ calendarEvent,
+}: {
+ existingCalendarEvent: ComparableCalendarEvent;
+ calendarEvent: Omit<ComparableCalendarEvent, 'id'>;
+}): boolean =>
+ TEXT_FIELD_NAMES.some(
+ (fieldName) =>
+ (existingCalendarEvent[fieldName] ?? '') !==
+ (calendarEvent[fieldName] ?? ''),
+ ) ||
+ DATE_TIME_FIELD_NAMES.some(
+ (fieldName) =>
+ toEpochMilliseconds(existingCalendarEvent[fieldName]) !==
+ toEpochMilliseconds(calendarEvent[fieldName]),
+ ) ||
+ BOOLEAN_FIELD_NAMES.some(
+ (fieldName) =>
+ existingCalendarEvent[fieldName] !== calendarEvent[fieldName],
+ ) ||
+ (existingCalendarEvent.conferenceLink?.primaryLinkLabel ?? '') !==
+ (calendarEvent.conferenceLink.primaryLinkLabel ?? '') ||
+ (existingCalendarEvent.conferenceLink?.primaryLinkUrl ?? '') !==
+ (calendarEvent.conferenceLink.primaryLinkUrl ?? '') ||
+ isNonEmptyArray(existingCalendarEvent.conferenceLink?.secondaryLinks);
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/utils/__tests__/build-calendar-event-participant-save-operations.util.spec.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/utils/__tests__/build-calendar-event-participant-save-operations.util.spec.ts
new file mode 100644
index 00000000000..fb780f377ec
--- /dev/null
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/utils/__tests__/build-calendar-event-participant-save-operations.util.spec.ts
@@ -0,0 +1,115 @@
+import { buildCalendarEventParticipantSaveOperations } from 'src/modules/calendar/calendar-event-participant-manager/utils/build-calendar-event-participant-save-operations.util';
+import { type CalendarEventParticipantWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event-participant.workspace-entity';
+import { type FetchedParticipantWithCalendarEventId } from 'src/modules/calendar/common/types/fetched-participant-with-calendar-event-id.type';
+
+const CALENDAR_EVENT_ID = 'calendar-event-id';
+
+const buildFetchedParticipant = (
+ overrides: Partial<FetchedParticipantWithCalendarEventId> = {},
+): FetchedParticipantWithCalendarEventId => ({
+ calendarEventId: CALENDAR_EVENT_ID,
+ handle: '[email protected]',
+ displayName: 'John Doe',
+ responseStatus: 'ACCEPTED',
+ isOrganizer: false,
+ ...overrides,
+});
+
+const buildExistingParticipant = (
+ overrides: Partial<CalendarEventParticipantWorkspaceEntity> = {},
+): CalendarEventParticipantWorkspaceEntity =>
+ ({
+ id: 'existing-participant-id',
+ calendarEventId: CALENDAR_EVENT_ID,
+ handle: '[email protected]',
+ displayName: 'John Doe',
+ responseStatus: 'ACCEPTED',
+ isOrganizer: false,
+ personId: 'person-id',
+ workspaceMemberId: null,
+ ...overrides,
+ }) as CalendarEventParticipantWorkspaceEntity;
+
+describe('buildCalendarEventParticipantSaveOperations', () => {
+ it('skips existing participants whose fields did not change', () => {
+ const operations = buildCalendarEventParticipantSaveOperations({
+ fetchedParticipants: [buildFetchedParticipant()],
+ existingParticipants: [buildExistingParticipant()],
+ shouldSkipUnchangedParticipants: true,
+ });
+
+ expect(operations).toEqual({
+ participantsToInsert: [],
+ participantsToUpdate: [],
+ participantIdsToDelete: [],
+ });
+ });
+
+ it('updates unchanged participants when skipping is disabled', () => {
+ const operations = buildCalendarEventParticipantSaveOperations({
+ fetchedParticipants: [buildFetchedParticipant()],
+ existingParticipants: [buildExistingParticipant()],
+ shouldSkipUnchangedParticipants: false,
+ });
+
+ expect(operations.participantsToUpdate).toEqual([
+ {
+ criteria: 'existing-participant-id',
+ partialEntity: buildFetchedParticipant(),
+ },
+ ]);
+ });
+
+ it('treats a null persisted display name as equal to an empty fetched one', () => {
+ const operations = buildCalendarEventParticipantSaveOperations({
+ fetchedParticipants: [buildFetchedParticipant({ displayName: '' })],
+ existingParticipants: [buildExistingParticipant({ displayName: null })],
+ shouldSkipUnchangedParticipants: true,
+ });
+
+ expect(operations.participantsToUpdate).toEqual([]);
+ });
+
+ it.each([
+ ['displayName', { displayName: 'Johnny Doe' }],
+ ['responseStatus', { responseStatus: 'DECLINED' }],
+ ['isOrganizer', { isOrganizer: true }],
+ ])('updates the participant when %s changed', (_, fetchedOverrides) => {
+ const fetchedParticipant = buildFetchedParticipant(fetchedOverrides);
+
+ const operations = buildCalendarEventParticipantSaveOperations({
+ fetchedParticipants: [fetchedParticipant],
+ existingParticipants: [buildExistingParticipant()],
+ shouldSkipUnchangedParticipants: true,
+ });
+
+ expect(operations.participantsToUpdate).toEqual([
+ {
+ criteria: 'existing-participant-id',
+ partialEntity: fetchedParticipant,
+ },
+ ]);
+ expect(operations.participantsToInsert).toEqual([]);
+ expect(operations.participantIdsToDelete).toEqual([]);
+ });
+
+ it('inserts new participants and deletes missing ones', () => {
+ const newParticipant = buildFetchedParticipant({
+ handle: '[email protected]',
+ });
+
+ const operations = buildCalendarEventParticipantSaveOperations({
+ fetchedParticipants: [newParticipant],
+ existingParticipants: [buildExistingParticipant()],
+ shouldSkipUnchangedParticipants: true,
+ });
+
+ expect(operations.participantsToInsert).toEqual([
+ { ...newParticipant, id: expect.any(String) },
+ ]);
+ expect(operations.participantsToUpdate).toEqual([]);
+ expect(operations.participantIdsToDelete).toEqual([
+ 'existing-participant-id',
+ ]);
+ });
+});
diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/utils/build-calendar-event-participant-save-operations.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/utils/build-calendar-event-participant-save-operations.util.ts
index 08eb6bcbdb2..b2bc7fa41f8 100644
--- a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/utils/build-calendar-event-participant-save-operations.util.ts
+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/utils/build-calendar-event-participant-save-operations.util.ts
@@ -13,12 +13,27 @@ const buildParticipantKey = ({
handle: string | null;
}): string => `${calendarEventId}:${handle}`;
+const hasParticipantChanged = ({
+ existingParticipant,
+ fetchedParticipant,
+}: {
+ existingParticipant: CalendarEventParticipantWorkspaceEntity;
+ fetchedParticipant: FetchedParticipantWithCalendarEventId;
+}): boolean =>
+ (existingParticipant.displayName ?? '') !==
+ (fetchedParticipant.displayName ?? '') ||
+ (existingParticipant.responseStatus ?? '') !==
+ (fetchedParticipant.responseStatus ?? '') ||
+ existingParticipant.isOrganizer !== fetchedParticipant.isOrganizer;
+
export const buildCalendarEventParticipantSaveOperations = ({
fetchedParticipants,
existingParticipants,
+ shouldSkipUnchangedParticipants,
}: {
fetchedParticipants: FetchedParticipantWithCalendarEventId[];
existingParticipants: CalendarEventParticipantWorkspaceEntity[];
+ shouldSkipUnchangedParticipants: boolean;
}): CalendarEventParticipantSaveOperations => {
const existingParticipantByKey = new Map<
string,
@@ -55,6 +70,13 @@ export const buildCalendarEventParticipantSaveOperations = ({
continue;
}
+ if (
+ shouldSkipUnchangedParticipants &&
+ !hasParticipantChanged({ existingParticipant, fetchedParticipant })
+ ) {
+ continue;
+ }
+
operations.participantsToUpdate.push({
criteria: existingParticipant.id,
partialEntity: fetchedParticipant,
diff --git a/packages/twenty-server/test/integration/google/calendar/transient-database-error.integration-spec.ts b/packages/twenty-server/test/integration/google/calendar/transient-database-error.integration-spec.ts
index 1556fe16bcd..922f0605e83 100644
--- a/packages/twenty-server/test/integration/google/calendar/transient-database-error.integration-spec.ts
+++ b/packages/twenty-server/test/integration/google/calendar/transient-database-error.integration-spec.ts
@@ -212,7 +212,7 @@ describe('Calendar import transient database errors (integration)', () => {
await runCalendarChannelEventsImport(channel.calendarChannelId);
expect(insertedHandles).toEqual([newAttendee]);
- expect(updatedParticipantCount).toBe(1);
+ expect(updatedParticipantCount).toBe(0);
}, 180000);
it('should read and compute outside the transaction and only write inside it', async () => {
diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.ts
index d4b6669974d..37dd2a7a5fa 100644
--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts
+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts
@@ -18,4 +18,5 @@ export enum FeatureFlagKey {
IS_VALIDATION_RULES_ENABLED = 'IS_VALIDATION_RULES_ENABLED',
IS_RECORD_LEVEL_SHARING_ENABLED = 'IS_RECORD_LEVEL_SHARING_ENABLED',
IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED = 'IS_WORKFLOW_SEND_CHAT_MESSAGE_ENABLED',
+ IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED = 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED',
}