The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Share calendar events across calendar channels (#28017)
neo7737dea50c43b00
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphqlindex 168ed05c280..1a120d55eca 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql@@ -2097,6 +2097,7 @@ enum FeatureFlagKey {IS_APPLICATION_WORKFLOWS_ENABLEDIS_APP_PREFERENCES_ENABLEDIS_ASYNC_CSV_EXPORT_ENABLED+ IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLEDIS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLEDIS_CONFIGURABLE_SEARCH_FIELDS_ENABLEDIS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLEDdiff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.tsindex 2d982eef733..6a7477ea0cd 100644--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts@@ -1347,7 +1347,7 @@ export interface FeatureFlag {__typename: 'FeatureFlag'}-export type FeatureFlagKey = 'IS_AI_CHAT_INBOX_ENABLED' | 'IS_APPLICATION_WORKFLOWS_ENABLED' | 'IS_APP_PREFERENCES_ENABLED' | 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_LOGS_SETTINGS_SECTION_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_MORPH_RELATION_HEAD_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_RECORD_LEVEL_SHARING_ENABLED' | 'IS_RECORD_SHARE_VISIBILITY_GATING_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT'+export type FeatureFlagKey = 'IS_AI_CHAT_INBOX_ENABLED' | 'IS_APPLICATION_WORKFLOWS_ENABLED' | 'IS_APP_PREFERENCES_ENABLED' | 'IS_ASYNC_CSV_EXPORT_ENABLED' | 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED' | 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED' | 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' | 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' | 'IS_JSON_FILTER_ENABLED' | 'IS_LOGS_SETTINGS_SECTION_ENABLED' | 'IS_MESSAGE_CAMPAIGN_ENABLED' | 'IS_MORPH_RELATION_HEAD_ENABLED' | 'IS_RECORD_CREATION_FORM_ENABLED' | 'IS_RECORD_LEVEL_SHARING_ENABLED' | 'IS_RECORD_SHARE_VISIBILITY_GATING_ENABLED' | 'IS_REST_METADATA_API_NEW_FORMAT_DIRECT'export interface Field {applicationId: Scalars['UUID']@@ -11574,6 +11574,7 @@ export const enumFeatureFlagKey = {IS_APPLICATION_WORKFLOWS_ENABLED: 'IS_APPLICATION_WORKFLOWS_ENABLED' as const,IS_APP_PREFERENCES_ENABLED: 'IS_APP_PREFERENCES_ENABLED' as const,IS_ASYNC_CSV_EXPORT_ENABLED: 'IS_ASYNC_CSV_EXPORT_ENABLED' as const,+ IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED: 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED' as const,IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED: 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED' as const,IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED: 'IS_CONFIGURABLE_SEARCH_FIELDS_ENABLED' as const,IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED: 'IS_DEFERRED_WORKSPACE_MIGRATION_ACTIONS_ENABLED' as const,diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.tsindex 9cc11eb3591..32b9adc0b28 100644--- a/packages/twenty-front/src/generated-admin/graphql.ts+++ b/packages/twenty-front/src/generated-admin/graphql.ts@@ -449,6 +449,7 @@ export enum FeatureFlagKey {IS_APPLICATION_WORKFLOWS_ENABLED = 'IS_APPLICATION_WORKFLOWS_ENABLED',IS_APP_PREFERENCES_ENABLED = 'IS_APP_PREFERENCES_ENABLED',IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',+ IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED = 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_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_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.tsindex 616f8130cb6..6086eb91493 100644--- a/packages/twenty-front/src/generated-metadata/graphql.ts+++ b/packages/twenty-front/src/generated-metadata/graphql.ts@@ -2216,6 +2216,7 @@ export enum FeatureFlagKey {IS_APPLICATION_WORKFLOWS_ENABLED = 'IS_APPLICATION_WORKFLOWS_ENABLED',IS_APP_PREFERENCES_ENABLED = 'IS_APP_PREFERENCES_ENABLED',IS_ASYNC_CSV_EXPORT_ENABLED = 'IS_ASYNC_CSV_EXPORT_ENABLED',+ IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED = 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_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_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.tsindex a1eab8dee56..f4794e6cb4c 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@@ -60,6 +60,10 @@ export const SETTINGS_ADMIN_FEATURE_FLAG_METADATA: Record<label: msg`Skip unchanged calendar records`,description: msg`Only write calendar events and participants that changed since the last sync.`,},+ [FeatureFlagKey.IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED]: {+ label: msg`Share calendar events across channels`,+ description: msg`Store a meeting synced by several calendars of the same provider once, instead of once per calendar.`,+ },[FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED]: {label: msg`AI chat inbox`,description: msg`Turn the AI tab into an inbox to triage, assign, snooze and follow chats, let workflows send messages and agent questions to a member's inbox, and show a Conversations tab on record pages.`,diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-upgrade-version-command.module.tsnew file mode 100644index 00000000000..a3b7a07a80f--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-upgrade-version-command.module.ts@@ -0,0 +1,18 @@+import { Module } from '@nestjs/common';++import { WorkspaceIteratorModule } from 'src/database/commands/command-runners/workspace-iterator.module';+import { AddCalendarEventSharingIndexesCommand } from 'src/database/commands/upgrade-version-command/2-49/2-49-workspace-command-1792153151454-add-calendar-event-sharing-indexes.command';+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';+import { WorkspaceCacheModule } from 'src/engine/workspace-cache/workspace-cache.module';+import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace-migration/workspace-migration.module';++@Module({+ imports: [+ ApplicationModule,+ WorkspaceCacheModule,+ WorkspaceIteratorModule,+ WorkspaceMigrationModule,+ ],+ providers: [AddCalendarEventSharingIndexesCommand],+})+export class V2_49_UpgradeVersionCommandModule {}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-workspace-command-1792153151454-add-calendar-event-sharing-indexes.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-workspace-command-1792153151454-add-calendar-event-sharing-indexes.command.tsnew file mode 100644index 00000000000..15c5c9c6f05--- /dev/null+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-49/2-49-workspace-command-1792153151454-add-calendar-event-sharing-indexes.command.ts@@ -0,0 +1,215 @@+import { Command } from 'nest-commander';+import { STANDARD_OBJECTS } from 'twenty-shared/metadata';+import { isDefined } from 'twenty-shared/utils';++import { ProvisionedWorkspaceCommandRunner } from 'src/database/commands/command-runners/provisioned-workspace.command-runner';+import { WorkspaceIteratorService } from 'src/database/commands/command-runners/workspace-iterator.service';+import { type RunOnWorkspaceArgs } from 'src/database/commands/command-runners/workspace.command-runner';+import { getStandardFlatEntitiesToCreateOrThrow } from 'src/database/commands/upgrade-version-command/2-10/utils/get-standard-flat-entities-to-create-or-throw.util';+import { ApplicationService } from 'src/engine/core-modules/application/application.service';+import { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';+import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';+import { type FlatFieldMetadata } from 'src/engine/metadata-modules/flat-field-metadata/types/flat-field-metadata.type';+import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';+import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';+import { computeTwentyStandardApplicationAllFlatEntityMaps } from 'src/engine/workspace-manager/twenty-standard-application/utils/twenty-standard-application-all-flat-entity-maps.constant';+import { WorkspaceMigrationBuilderException } from 'src/engine/workspace-manager/workspace-migration/exceptions/workspace-migration-builder-exception';+import { WorkspaceMigrationValidateBuildAndRunService } from 'src/engine/workspace-manager/workspace-migration/services/workspace-migration-validate-build-and-run-service';++const CALENDAR_EVENT_SHARING_INDEXES = [+ {+ indexUniversalIdentifier:+ STANDARD_OBJECTS.calendarChannelEventAssociation.indexes+ .eventExternalIdIndex.universalIdentifier,+ objectUniversalIdentifier:+ STANDARD_OBJECTS.calendarChannelEventAssociation.universalIdentifier,+ fieldUniversalIdentifier:+ STANDARD_OBJECTS.calendarChannelEventAssociation.fields.eventExternalId+ .universalIdentifier,+ },+ {+ indexUniversalIdentifier:+ STANDARD_OBJECTS.calendarEvent.indexes.iCalUidIndex.universalIdentifier,+ objectUniversalIdentifier:+ STANDARD_OBJECTS.calendarEvent.universalIdentifier,+ fieldUniversalIdentifier:+ STANDARD_OBJECTS.calendarEvent.fields.iCalUid.universalIdentifier,+ },+];++const CALENDAR_EVENT_SHARING_INDEX_UNIVERSAL_IDENTIFIERS =+ CALENDAR_EVENT_SHARING_INDEXES.map(+ ({ indexUniversalIdentifier }) => indexUniversalIdentifier,+ );++@RegisteredWorkspaceCommand('2.49.0', 1792153151454)+@Command({+ name: 'upgrade:2-49:add-calendar-event-sharing-indexes',+ description:+ 'Index calendarChannelEventAssociation.eventExternalId and calendarEvent.iCalUid so calendar import can find another channel copy of an event',+})+export class AddCalendarEventSharingIndexesCommand extends ProvisionedWorkspaceCommandRunner {+ constructor(+ protected readonly workspaceIteratorService: WorkspaceIteratorService,+ private readonly applicationService: ApplicationService,+ private readonly workspaceCacheService: WorkspaceCacheService,+ private readonly workspaceMigrationValidateBuildAndRunService: WorkspaceMigrationValidateBuildAndRunService,+ ) {+ super(workspaceIteratorService);+ }++ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {+ await this.up(args);+ }++ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {+ const { flatObjectMetadataMaps, flatFieldMetadataMaps, flatIndexMaps } =+ await this.workspaceCacheService.getOrRecompute(workspaceId, [+ 'flatObjectMetadataMaps',+ 'flatFieldMetadataMaps',+ 'flatIndexMaps',+ ]);++ const indexUniversalIdentifiersToCreate =+ CALENDAR_EVENT_SHARING_INDEXES.filter(+ ({ objectUniversalIdentifier, fieldUniversalIdentifier }) =>+ isDefined(+ findFlatEntityByUniversalIdentifier<FlatObjectMetadata>({+ flatEntityMaps: flatObjectMetadataMaps,+ universalIdentifier: objectUniversalIdentifier,+ }),+ ) &&+ isDefined(+ findFlatEntityByUniversalIdentifier<FlatFieldMetadata>({+ flatEntityMaps: flatFieldMetadataMaps,+ universalIdentifier: fieldUniversalIdentifier,+ }),+ ),+ ).map(({ indexUniversalIdentifier }) => indexUniversalIdentifier);++ if (indexUniversalIdentifiersToCreate.length === 0) {+ this.logger.log(+ `Calendar objects not found for workspace ${workspaceId}, skipping`,+ );++ return;+ }++ const { twentyStandardFlatApplication } =+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(+ { workspaceId },+ );++ const { allFlatEntityMaps: standardAllFlatEntityMaps } =+ computeTwentyStandardApplicationAllFlatEntityMaps({+ now: new Date().toISOString(),+ workspaceId,+ twentyStandardApplicationId: twentyStandardFlatApplication.id,+ });++ const indexesToCreate =+ getStandardFlatEntitiesToCreateOrThrow<FlatIndexMetadata>({+ standardFlatEntityMaps: standardAllFlatEntityMaps.flatIndexMaps,+ existingFlatEntityMaps: flatIndexMaps,+ universalIdentifiers: indexUniversalIdentifiersToCreate,+ });++ if (indexesToCreate.length === 0) {+ return;+ }++ if (options.dryRun) {+ this.logger.log(+ `[DRY RUN] Would create ${indexesToCreate.length} calendar event sharing index(es) for workspace ${workspaceId}`,+ );++ return;+ }++ await this.runIndexMigration({+ workspaceId,+ applicationUniversalIdentifier:+ twentyStandardFlatApplication.universalIdentifier,+ flatEntityToCreate: indexesToCreate,+ flatEntityToDelete: [],+ });++ this.logger.log(+ `Created ${indexesToCreate.length} calendar event sharing index(es) for workspace ${workspaceId}`,+ );+ }++ async down({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {+ const { flatIndexMaps } = await this.workspaceCacheService.getOrRecompute(+ workspaceId,+ ['flatIndexMaps'],+ );++ const indexesToDelete =+ CALENDAR_EVENT_SHARING_INDEX_UNIVERSAL_IDENTIFIERS.map(+ (universalIdentifier) =>+ findFlatEntityByUniversalIdentifier<FlatIndexMetadata>({+ flatEntityMaps: flatIndexMaps,+ universalIdentifier,+ }),+ ).filter(isDefined);++ if (indexesToDelete.length === 0) {+ return;+ }++ if (options.dryRun) {+ this.logger.log(+ `[DRY RUN] Would drop ${indexesToDelete.length} calendar event sharing index(es) for workspace ${workspaceId}`,+ );++ return;+ }++ const { twentyStandardFlatApplication } =+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(+ { workspaceId },+ );++ await this.runIndexMigration({+ workspaceId,+ applicationUniversalIdentifier:+ twentyStandardFlatApplication.universalIdentifier,+ flatEntityToCreate: [],+ flatEntityToDelete: indexesToDelete,+ });+ }++ private async runIndexMigration({+ workspaceId,+ applicationUniversalIdentifier,+ flatEntityToCreate,+ flatEntityToDelete,+ }: {+ workspaceId: string;+ applicationUniversalIdentifier: string;+ flatEntityToCreate: FlatIndexMetadata[];+ flatEntityToDelete: FlatIndexMetadata[];+ }): Promise<void> {+ const result =+ await this.workspaceMigrationValidateBuildAndRunService.validateBuildAndRunLegacyWorkspaceMigration(+ {+ isSystemBuild: true,+ applicationUniversalIdentifier,+ workspaceId,+ allFlatEntityOperationByMetadataName: {+ index: {+ flatEntityToCreate,+ flatEntityToDelete,+ flatEntityToUpdate: [],+ },+ },+ },+ );++ if (result.status === 'fail') {+ throw new WorkspaceMigrationBuilderException(result);+ }+ }+}diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/workspace-command-provider.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/workspace-command-provider.module.tsindex c8227465cce..645239506d6 100644--- a/packages/twenty-server/src/database/commands/upgrade-version-command/workspace-command-provider.module.ts+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/workspace-command-provider.module.ts@@ -41,6 +41,7 @@ import { V2_45_UpgradeVersionCommandModule } from 'src/database/commands/upgradeimport { V2_46_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-46/2-46-upgrade-version-command.module';import { V2_47_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-47/2-47-upgrade-version-command.module';import { V2_48_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-48/2-48-upgrade-version-command.module';+import { V2_49_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-49/2-49-upgrade-version-command.module';import { V2_4_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-4/2-4-upgrade-version-command.module';import { V2_5_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-5/2-5-upgrade-version-command.module';import { V2_7_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-version-command/2-7/2-7-upgrade-version-command.module';@@ -95,6 +96,7 @@ import { V2_9_UpgradeVersionCommandModule } from 'src/database/commands/upgrade-V2_46_UpgradeVersionCommandModule,V2_47_UpgradeVersionCommandModule,V2_48_UpgradeVersionCommandModule,+ V2_49_UpgradeVersionCommandModule,],})export class WorkspaceCommandProviderModule {}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.tsindex b927b6b3613..94676f7e70d 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@@ -9,6 +9,7 @@ const DEFAULT_SEEDED_FEATURE_FLAGS: Partial<Record<FeatureFlagKey, boolean>> = {[FeatureFlagKey.IS_LOGS_SETTINGS_SECTION_ENABLED]: true,[FeatureFlagKey.IS_RECORD_LEVEL_SHARING_ENABLED]: false,[FeatureFlagKey.IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED]: true,+ [FeatureFlagKey.IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED]: true,[FeatureFlagKey.IS_AI_CHAT_INBOX_ENABLED]: true,};diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/build-standard-flat-index-metadata-maps.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/build-standard-flat-index-metadata-maps.util.tsindex 3feb6b4cb6e..1177d522ad0 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/build-standard-flat-index-metadata-maps.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/build-standard-flat-index-metadata-maps.util.ts@@ -15,6 +15,7 @@ import { type AllStandardObjectName } from 'src/engine/workspace-manager/twenty-import { buildAttachmentStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-attachment-standard-flat-index-metadata.util';import { buildBlocklistStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-blocklist-standard-flat-index-metadata.util';import { buildCalendarChannelEventAssociationStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-channel-event-association-standard-flat-index-metadata.util';+import { buildCalendarEventStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-event-standard-flat-index-metadata.util';import { buildCalendarEventParticipantStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-event-participant-standard-flat-index-metadata.util';import { buildCalendarEventTargetStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-event-target-standard-flat-index-metadata.util';import { buildCallRecordingStandardFlatIndexMetadatas } from 'src/engine/workspace-manager/twenty-standard-application/utils/index/compute-call-recording-standard-flat-index-metadata.util';@@ -63,6 +64,7 @@ const STANDARD_FLAT_INDEX_METADATA_BUILDERS_BY_OBJECT_NAME = {blocklist: buildBlocklistStandardFlatIndexMetadatas,calendarChannelEventAssociation:buildCalendarChannelEventAssociationStandardFlatIndexMetadatas,+ calendarEvent: buildCalendarEventStandardFlatIndexMetadatas,calendarEventParticipant:buildCalendarEventParticipantStandardFlatIndexMetadatas,calendarEventTarget: buildCalendarEventTargetStandardFlatIndexMetadatas,diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-channel-event-association-standard-flat-index-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-channel-event-association-standard-flat-index-metadata.util.tsindex eb1077e8758..155abb200dc 100644--- a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-channel-event-association-standard-flat-index-metadata.util.ts+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-channel-event-association-standard-flat-index-metadata.util.ts@@ -43,4 +43,16 @@ export const buildCalendarChannelEventAssociationStandardFlatIndexMetadatas = ({twentyStandardApplicationId,now,}),+ eventExternalIdIndex: createStandardIndexFlatMetadata({+ objectName,+ workspaceId,+ context: {+ indexName: 'eventExternalIdIndex',+ relatedFieldNames: ['eventExternalId'],+ },+ standardObjectMetadataRelatedEntityIds,+ dependencyFlatEntityMaps,+ twentyStandardApplicationId,+ now,+ }),});diff --git a/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-event-standard-flat-index-metadata.util.ts b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-event-standard-flat-index-metadata.util.tsnew file mode 100644index 00000000000..9df50983b67--- /dev/null+++ b/packages/twenty-server/src/engine/workspace-manager/twenty-standard-application/utils/index/compute-calendar-event-standard-flat-index-metadata.util.ts@@ -0,0 +1,31 @@+import { type FlatIndexMetadata } from 'src/engine/metadata-modules/flat-index-metadata/types/flat-index-metadata.type';+import { type AllStandardObjectIndexName } from 'src/engine/workspace-manager/twenty-standard-application/types/all-standard-object-index-name.type';+import {+ type CreateStandardIndexArgs,+ createStandardIndexFlatMetadata,+} from 'src/engine/workspace-manager/twenty-standard-application/utils/index/create-standard-index-flat-metadata.util';++export const buildCalendarEventStandardFlatIndexMetadatas = ({+ now,+ objectName,+ workspaceId,+ standardObjectMetadataRelatedEntityIds,+ dependencyFlatEntityMaps,+ twentyStandardApplicationId,+}: Omit<CreateStandardIndexArgs<'calendarEvent'>, 'context'>): Record<+ AllStandardObjectIndexName<'calendarEvent'>,+ FlatIndexMetadata+> => ({+ iCalUidIndex: createStandardIndexFlatMetadata({+ objectName,+ workspaceId,+ context: {+ indexName: 'iCalUidIndex',+ relatedFieldNames: ['iCalUid'],+ },+ standardObjectMetadataRelatedEntityIds,+ dependencyFlatEntityMaps,+ twentyStandardApplicationId,+ now,+ }),+});diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/drivers/caldav/services/caldav-create-event.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/drivers/caldav/services/caldav-create-event.service.tsindex f78db5c5200..9bea6fa7b6d 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/drivers/caldav/services/caldav-create-event.service.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-creation-manager/drivers/caldav/services/caldav-create-event.service.ts@@ -100,6 +100,7 @@ export class CalDavCreateEventService implements CalendarEventCreationDriver {isCanceled: false,isPrivate: false,status: 'CONFIRMED',+ organizerHandle: '',conferenceLinkLabel: '',conferenceLinkUrl: '',conferenceSolution: '',diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/caldav/utils/parse-ical-event.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/caldav/utils/parse-ical-event.util.tsindex ae8a5a3a0b1..14689a17f91 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/caldav/utils/parse-ical-event.util.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/caldav/utils/parse-ical-event.util.ts@@ -48,6 +48,7 @@ export const parseICalEvents = ('PUBLIC',status: event.status || 'CONFIRMED',recurringEventExternalId: recurrenceIso,+ organizerHandle: '',conferenceLinkLabel: '',conferenceLinkUrl: icalDataExtractPropertyValue(event.url),conferenceSolution: '',diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/format-google-calendar-event.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/format-google-calendar-event.util.tsindex 79a7401da5f..3a6d2baed50 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/format-google-calendar-event.util.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/google-calendar/utils/format-google-calendar-event.util.ts@@ -45,6 +45,7 @@ const formatGoogleCalendarEvent = (conferenceLinkLabel: event.conferenceData?.entryPoints?.[0]?.uri ?? '',conferenceLinkUrl: event.conferenceData?.entryPoints?.[0]?.uri ?? '',recurringEventExternalId: event.recurringEventId ?? '',+ organizerHandle: event.organizer?.email?.toLowerCase() ?? '',participants:event.attendees?.map((attendee) => ({handle: attendee.email?.toLowerCase() ?? '',@@ -69,6 +70,7 @@ const formatGoogleCalendarEvent = ('conferenceLinkLabel','conferenceLinkUrl','recurringEventExternalId',+ 'organizerHandle','status',];diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/format-microsoft-calendar-event.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/format-microsoft-calendar-event.util.tsindex 0798a98341f..e22fe0ba287 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/format-microsoft-calendar-event.util.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/drivers/microsoft-calendar/utils/format-microsoft-calendar-event.util.ts@@ -49,6 +49,8 @@ const formatMicrosoftCalendarEvent = (event: Event): FetchedCalendarEvent => {conferenceLinkLabel: event.onlineMeeting?.joinUrl ?? '',conferenceLinkUrl: event.onlineMeeting?.joinUrl ?? '',recurringEventExternalId: event.id ?? '',+ organizerHandle:+ event.organizer?.emailAddress?.address?.toLowerCase() ?? '',participants:event.attendees?.map((attendee) => ({handle: attendee.emailAddress?.address?.toLowerCase() ?? '',@@ -73,6 +75,7 @@ const formatMicrosoftCalendarEvent = (event: Event): FetchedCalendarEvent => {'conferenceLinkLabel','conferenceLinkUrl','recurringEventExternalId',+ 'organizerHandle','status',];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.tsindex cbada2e0897..c261819570d 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,14 +1,22 @@import { Injectable } from '@nestjs/common';-import { FeatureFlagKey } from 'twenty-shared/types';-import { Any } from 'typeorm';+import { isNonEmptyString } from '@sniptt/guards';+import { ConnectedAccountProvider, FeatureFlagKey } from 'twenty-shared/types';+import { assertUnreachable } from 'twenty-shared/utils';+import { Any, In, Not } 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 { 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 { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';+import { type CalendarEventSharingChannel } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-sharing-channel.type';import { buildCalendarEventSaveOperations } from 'src/modules/calendar/calendar-event-import-manager/utils/build-calendar-event-save-operations.util';+import { getCalendarChannelHandles } from 'src/modules/calendar/calendar-event-import-manager/utils/get-calendar-channel-handles.util';+import { resolveCalendarEventSharing } from 'src/modules/calendar/calendar-event-import-manager/utils/resolve-calendar-event-sharing.util';import { CalendarEventParticipantService } from 'src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service';import { buildCalendarEventParticipantSaveOperations } from 'src/modules/calendar/calendar-event-participant-manager/utils/build-calendar-event-participant-save-operations.util';import { type CalendarChannelEventAssociationWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-channel-event-association.workspace-entity';@@ -21,6 +29,8 @@ export class CalendarSaveEventsService {private readonly workspaceOrmManager: WorkspaceOrmManager,private readonly calendarEventParticipantService: CalendarEventParticipantService,private readonly featureFlagService: FeatureFlagService,+ @InjectWorkspaceScopedRepository(CalendarChannelEntity)+ private readonly calendarChannelRepository: WorkspaceScopedRepository<CalendarChannelEntity>,) {}public async saveCalendarEventsAndEnqueueContactCreationJob(@@ -37,140 +47,258 @@ export class CalendarSaveEventsService {workspaceId,);- const { savedParticipantIds, calendarEventIds } =- await this.workspaceOrmManager.executeInWorkspaceContext(- async () => {- const calendarChannelEventAssociationRepository =- this.workspaceOrmManager.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(- 'calendarChannelEventAssociation',- { shouldBypassPermissionChecks: true },- );+ const isCalendarEventSharingEnabled =+ await this.featureFlagService.isFeatureEnabled(+ FeatureFlagKey.IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED,+ workspaceId,+ );- const existingAssociations =- await calendarChannelEventAssociationRepository.find({- where: {- eventExternalId: Any(- fetchedCalendarEvents.map((event) => event.id),- ),- calendarChannelId: calendarChannel.id,- },- });+ const channelHandles = getCalendarChannelHandles({+ calendarChannel,+ connectedAccount,+ });- const calendarEventRepository =- this.workspaceOrmManager.getRepository<CalendarEventWorkspaceEntity>(- 'calendarEvent',- { shouldBypassPermissionChecks: true },- );+ const {+ savedParticipantIds,+ participantsOfLinkedEvents,+ calendarEventIds,+ } = await this.workspaceOrmManager.executeInWorkspaceContext(+ async () => {+ const calendarChannelEventAssociationRepository =+ this.workspaceOrmManager.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(+ 'calendarChannelEventAssociation',+ { shouldBypassPermissionChecks: true },+ );- const existingCalendarEvents = shouldSkipUnchangedRecords- ? await calendarEventRepository.find({+ const calendarEventRepository =+ this.workspaceOrmManager.getRepository<CalendarEventWorkspaceEntity>(+ 'calendarEvent',+ { shouldBypassPermissionChecks: true },+ );++ const existingAssociations =+ await calendarChannelEventAssociationRepository.find({+ where: {+ eventExternalId: Any(+ fetchedCalendarEvents.map((event) => event.id),+ ),+ calendarChannelId: calendarChannel.id,+ },+ });++ const existingEventExternalIds = new Set(+ existingAssociations+ .map(({ eventExternalId }) => eventExternalId)+ .filter(isNonEmptyString),+ );++ // Not gated by the flag: events shared before it was turned off keep their roles+ const otherAssociationsOfExistingEvents =+ existingAssociations.length > 0+ ? await calendarChannelEventAssociationRepository.find({where: {- id: Any(+ calendarEventId: Any(existingAssociations.map(- (association) => association.calendarEventId,+ ({ calendarEventId }) => calendarEventId,),),+ calendarChannelId: Not(calendarChannel.id),+ },+ })+ : [];++ const linkCandidateAssociations = isCalendarEventSharingEnabled+ ? await this.findLinkCandidateAssociations({+ calendarChannelEventAssociationRepository,+ provider: connectedAccount.provider,+ calendarChannelId: calendarChannel.id,+ fetchedCalendarEvents: fetchedCalendarEvents.filter(+ ({ id }) => !existingEventExternalIds.has(id),+ ),+ })+ : [];++ const otherAssociations = [+ ...otherAssociationsOfExistingEvents,+ ...linkCandidateAssociations,+ ];++ const otherCalendarChannels: CalendarEventSharingChannel[] =+ otherAssociations.length > 0+ ? await this.calendarChannelRepository.find(workspaceId, {+ where: {+ id: In([+ ...new Set(+ otherAssociations.map(+ ({ calendarChannelId }) => calendarChannelId,+ ),+ ),+ ]),+ connectedAccount: { provider: connectedAccount.provider },+ },+ relations: { connectedAccount: true },+ select: {+ id: true,+ handle: true,+ syncStatus: true,+ isSyncEnabled: true,+ connectedAccount: { id: true, handleAliases: true },},}): [];- const {- saveOperations,- existingCalendarEventIds,- participantsOfNewEvents,- participantsOfExistingEvents,- } = buildCalendarEventSaveOperations({- fetchedCalendarEvents,- existingAssociations,- existingCalendarEvents,- calendarChannelId: calendarChannel.id,+ const otherCalendarChannelIds = new Set(+ otherCalendarChannels.map(({ id }) => id),+ );++ const sharedAssociations = otherAssociations.filter(+ ({ calendarChannelId }) =>+ otherCalendarChannelIds.has(calendarChannelId),+ );++ const candidateCalendarEventIds = [+ ...new Set(+ [...existingAssociations, ...sharedAssociations].map(+ ({ calendarEventId }) => calendarEventId,+ ),+ ),+ ];++ const candidateCalendarEvents =+ candidateCalendarEventIds.length > 0 &&+ (shouldSkipUnchangedRecords || sharedAssociations.length > 0)+ ? await calendarEventRepository.find({+ where: { id: Any(candidateCalendarEventIds) },+ })+ : [];++ const {+ calendarEventIdToLinkByEventExternalId,+ otherChannelIdsByCalendarEventId,+ } = resolveCalendarEventSharing({+ provider: connectedAccount.provider,+ fetchedCalendarEvents,+ existingEventExternalIds,+ sharedAssociations,+ iCalUidByCalendarEventId: new Map(+ candidateCalendarEvents.map(({ id, iCalUid }) => [id, iCalUid]),+ ),+ isCalendarEventSharingEnabled,+ });++ const storedCalendarEventIds = [+ ...existingAssociations.map(+ (association) => association.calendarEventId,+ ),+ ...calendarEventIdToLinkByEventExternalId.values(),+ ];++ const {+ saveOperations,+ existingCalendarEventIds,+ channelRoleByCalendarEventId,+ participantsOfNewEvents,+ participantsOfExistingEvents,+ participantsOfLinkedEvents,+ } = buildCalendarEventSaveOperations({+ fetchedCalendarEvents,+ existingAssociations,+ existingCalendarEvents: shouldSkipUnchangedRecords+ ? candidateCalendarEvents+ : [],+ calendarChannelId: calendarChannel.id,+ channelHandles,+ calendarEventIdToLinkByEventExternalId,+ otherChannelIdsByCalendarEventId,+ otherCalendarChannels,+ });++ const existingParticipants =+ await this.calendarEventParticipantService.findCalendarEventParticipantsByCalendarEventIds(+ { calendarEventIds: storedCalendarEventIds },+ );++ const participantOperations =+ buildCalendarEventParticipantSaveOperations({+ fetchedParticipants: [+ ...participantsOfNewEvents,+ ...participantsOfExistingEvents,+ ...participantsOfLinkedEvents,+ ],+ existingParticipants,+ shouldSkipUnchangedParticipants: shouldSkipUnchangedRecords,+ channelRoleByCalendarEventId,+ channelHandles,});- const existingParticipants =- await this.calendarEventParticipantService.findCalendarEventParticipantsByCalendarEventIds(+ await this.workspaceOrmManager.runInWorkspaceTransaction(+ async (transactionScope) => {+ const calendarEventRepository =+ transactionScope.getRepository<CalendarEventWorkspaceEntity>(+ 'calendarEvent',+ { shouldBypassPermissionChecks: true },+ );++ const associationRepository =+ transactionScope.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(+ 'calendarChannelEventAssociation',+ { shouldBypassPermissionChecks: true },+ );++ if (saveOperations.calendarEventsToInsert.length > 0) {+ await calendarEventRepository.insert(+ saveOperations.calendarEventsToInsert,+ );+ }++ if (saveOperations.calendarEventsToUpdate.length > 0) {+ await calendarEventRepository.updateMany(+ saveOperations.calendarEventsToUpdate,+ );+ }++ if (saveOperations.associationsToInsert.length > 0) {+ await associationRepository.insert(+ saveOperations.associationsToInsert,+ );+ }++ if (saveOperations.associationsToUpdate.length > 0) {+ await associationRepository.updateMany(+ saveOperations.associationsToUpdate,+ );+ }++ await this.calendarEventParticipantService.writeCalendarEventParticipants({- calendarEventIds: participantsOfExistingEvents.map(- (participant) => participant.calendarEventId,- ),+ operations: participantOperations,+ transactionScope,},);+ },+ );- const participantOperations =- buildCalendarEventParticipantSaveOperations({- fetchedParticipants: [- ...participantsOfNewEvents,- ...participantsOfExistingEvents,- ],- existingParticipants,- shouldSkipUnchangedParticipants: shouldSkipUnchangedRecords,- });-- await this.workspaceOrmManager.runInWorkspaceTransaction(- async (transactionScope) => {- const calendarEventRepository =- transactionScope.getRepository<CalendarEventWorkspaceEntity>(- 'calendarEvent',- { shouldBypassPermissionChecks: true },- );-- const associationRepository =- transactionScope.getRepository<CalendarChannelEventAssociationWorkspaceEntity>(- 'calendarChannelEventAssociation',- { shouldBypassPermissionChecks: true },- );-- if (saveOperations.calendarEventsToInsert.length > 0) {- await calendarEventRepository.insert(- saveOperations.calendarEventsToInsert,- );- }-- if (saveOperations.calendarEventsToUpdate.length > 0) {- await calendarEventRepository.updateMany(- saveOperations.calendarEventsToUpdate,- );- }-- if (saveOperations.associationsToInsert.length > 0) {- await associationRepository.insert(- saveOperations.associationsToInsert,- );- }-- if (saveOperations.associationsToUpdate.length > 0) {- await associationRepository.updateMany(- saveOperations.associationsToUpdate,- );- }-- await this.calendarEventParticipantService.writeCalendarEventParticipants(- {- operations: participantOperations,- transactionScope,- },- );- },- );-- return {- savedParticipantIds: participantOperations.participantsToInsert.map(- (participant) => participant.id,+ return {+ savedParticipantIds: participantOperations.participantsToInsert.map(+ (participant) => participant.id,+ ),+ participantsOfLinkedEvents,+ calendarEventIds: [+ ...saveOperations.associationsToInsert.map(+ ({ calendarEventId }) => calendarEventId,),- calendarEventIds: [- ...saveOperations.associationsToInsert.map(- ({ calendarEventId }) => calendarEventId,- ),- ...existingCalendarEventIds,- ],- };- },- authContext,- { lite: true },- );+ ...existingCalendarEventIds,+ ],+ };+ },+ authContext,+ { lite: true },+ );await this.calendarEventParticipantService.matchParticipantsAndEnqueueContactCreationJob({savedParticipantIds,+ participantsOfLinkedEvents,calendarEventIds,calendarChannel,connectedAccount,@@ -180,4 +308,52 @@ export class CalendarSaveEventsService {return { calendarEventIds };}++ private async findLinkCandidateAssociations({+ calendarChannelEventAssociationRepository,+ provider,+ calendarChannelId,+ fetchedCalendarEvents,+ }: {+ calendarChannelEventAssociationRepository: WorkspaceRepository<CalendarChannelEventAssociationWorkspaceEntity>;+ provider: ConnectedAccountProvider;+ calendarChannelId: string;+ fetchedCalendarEvents: FetchedCalendarEvent[];+ }): Promise<CalendarChannelEventAssociationWorkspaceEntity[]> {+ if (fetchedCalendarEvents.length === 0) {+ return [];+ }++ switch (provider) {+ case ConnectedAccountProvider.GOOGLE:+ return calendarChannelEventAssociationRepository.find({+ where: {+ eventExternalId: Any(fetchedCalendarEvents.map(({ id }) => id)),+ calendarChannelId: Not(calendarChannelId),+ },+ });+ case ConnectedAccountProvider.MICROSOFT: {+ const iCalUids = fetchedCalendarEvents+ .map(({ iCalUid }) => iCalUid)+ .filter(isNonEmptyString);++ return iCalUids.length > 0+ ? calendarChannelEventAssociationRepository.find({+ where: {+ calendarEvent: { iCalUid: Any(iCalUids) },+ calendarChannelId: Not(calendarChannelId),+ },+ })+ : [];+ }+ case ConnectedAccountProvider.IMAP_SMTP_CALDAV:+ case ConnectedAccountProvider.OIDC:+ case ConnectedAccountProvider.SAML:+ case ConnectedAccountProvider.EMAIL_GROUP:+ case ConnectedAccountProvider.APP:+ return [];+ default:+ return assertUnreachable(provider);+ }+ }}diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-channel-role.type.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-channel-role.type.tsnew file mode 100644index 00000000000..9f8dcae876a--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-channel-role.type.ts@@ -0,0 +1,5 @@+export type CalendarEventChannelRole =+ | 'ONLY_CHANNEL'+ | 'ORGANIZER_CHANNEL'+ | 'ATTENDEE_CHANNEL'+ | 'ATTENDEE_CHANNEL_WITH_ORGANIZER_SYNCING';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.tsindex b91a629c47e..db37c4e5c20 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@@ -1,9 +1,12 @@+import { type CalendarEventChannelRole } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-channel-role.type';import { type CalendarEventSaveOperations } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-save-operations.type';import { type FetchedParticipantWithCalendarEventId } from 'src/modules/calendar/common/types/fetched-participant-with-calendar-event-id.type';export type CalendarEventSavePlan = {saveOperations: CalendarEventSaveOperations;existingCalendarEventIds: string[];+ channelRoleByCalendarEventId: Map<string, CalendarEventChannelRole>;participantsOfNewEvents: FetchedParticipantWithCalendarEventId[];participantsOfExistingEvents: FetchedParticipantWithCalendarEventId[];+ participantsOfLinkedEvents: FetchedParticipantWithCalendarEventId[];};diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-sharing-channel.type.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-sharing-channel.type.tsnew file mode 100644index 00000000000..1f17b68b604--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/types/calendar-event-sharing-channel.type.ts@@ -0,0 +1,9 @@+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';++export type CalendarEventSharingChannel = Pick<+ CalendarChannelEntity,+ 'id' | 'handle' | 'isSyncEnabled' | 'syncStatus'+> & {+ connectedAccount: Pick<ConnectedAccountEntity, 'handleAliases'>;+};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.tsindex bfd5158484d..ef476848b4c 100644--- 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@@ -1,3 +1,6 @@+import { CalendarChannelSyncStatus } from 'twenty-shared/types';++import { type CalendarEventSharingChannel } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-sharing-channel.type';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';@@ -7,6 +10,7 @@ import { type FetchedCalendarEvent } from 'src/modules/calendar/common/types/fetconst CALENDAR_CHANNEL_ID = 'calendar-channel-id';const CALENDAR_EVENT_ID = 'calendar-event-id';const ASSOCIATION_ID = 'association-id';+const CHANNEL_HANDLE = '[email protected]';const buildExistingCalendarEvent = (overrides: Partial<ComparableCalendarEvent> = {},@@ -41,13 +45,57 @@ const buildExistingAssociation = (...overrides,}) as CalendarChannelEventAssociationWorkspaceEntity;+const buildCalendarChannel = ({+ id,+ handle,+}: {+ id: string;+ handle: string;+}): CalendarEventSharingChannel => ({+ id,+ handle,+ syncStatus: CalendarChannelSyncStatus.ACTIVE,+ isSyncEnabled: true,+ connectedAccount: { handleAliases: [] },+});++const ATTENDEE_CHANNEL = buildCalendarChannel({+ id: 'attendee-channel-id',+ handle: '[email protected]',+});++const buildPlan = ({+ fetchedCalendarEvents,+ existingAssociations,+ existingCalendarEvents,+ calendarEventIdToLinkByEventExternalId = new Map(),+ otherCalendarChannels = [],+}: {+ fetchedCalendarEvents: FetchedCalendarEvent[];+ existingAssociations: CalendarChannelEventAssociationWorkspaceEntity[];+ existingCalendarEvents: ComparableCalendarEvent[];+ calendarEventIdToLinkByEventExternalId?: Map<string, string>;+ otherCalendarChannels?: CalendarEventSharingChannel[];+}) =>+ buildCalendarEventSaveOperations({+ fetchedCalendarEvents,+ existingAssociations,+ existingCalendarEvents,+ calendarChannelId: CALENDAR_CHANNEL_ID,+ channelHandles: [CHANNEL_HANDLE],+ calendarEventIdToLinkByEventExternalId,+ otherChannelIdsByCalendarEventId: new Map([+ [CALENDAR_EVENT_ID, otherCalendarChannels.map(({ id }) => id)],+ ]),+ otherCalendarChannels,+ });+describe('buildCalendarEventSaveOperations', () => {it('skips updates for an existing event that did not change', () => {- const plan = buildCalendarEventSaveOperations({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent()],existingAssociations: [buildExistingAssociation()],existingCalendarEvents: [buildExistingCalendarEvent()],- calendarChannelId: CALENDAR_CHANNEL_ID,});expect(plan.saveOperations).toEqual({@@ -69,7 +117,7 @@ describe('buildCalendarEventSaveOperations', () => {});it('ignores provider bookkeeping timestamps when nothing else changed', () => {- const plan = buildCalendarEventSaveOperations({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent({externalCreatedAt: '2026-10-02T15:00:00.000Z',@@ -78,14 +126,13 @@ describe('buildCalendarEventSaveOperations', () => {],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({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent({startsAt: '2026-10-02T08:00:00.0000000',@@ -94,18 +141,16 @@ describe('buildCalendarEventSaveOperations', () => {],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({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent({ endsAt: '' })],existingAssociations: [buildExistingAssociation()],existingCalendarEvents: [buildExistingCalendarEvent({ endsAt: null })],- calendarChannelId: CALENDAR_CHANNEL_ID,});expect(plan.saveOperations.calendarEventsToUpdate).toEqual([]);@@ -138,11 +183,10 @@ describe('buildCalendarEventSaveOperations', () => {])('updates an existing event when its %s changed',(_, overrides, written) => {- const plan = buildCalendarEventSaveOperations({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent(overrides)],existingAssociations: [buildExistingAssociation()],existingCalendarEvents: [buildExistingCalendarEvent()],- calendarChannelId: CALENDAR_CHANNEL_ID,});expect(plan.saveOperations.calendarEventsToUpdate).toEqual([@@ -156,7 +200,7 @@ describe('buildCalendarEventSaveOperations', () => {);it('updates an existing event that has secondary links to clear them', () => {- const plan = buildCalendarEventSaveOperations({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent()],existingAssociations: [buildExistingAssociation()],existingCalendarEvents: [@@ -168,18 +212,16 @@ describe('buildCalendarEventSaveOperations', () => {},}),],- 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({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent()],existingAssociations: [buildExistingAssociation()],existingCalendarEvents: [],- calendarChannelId: CALENDAR_CHANNEL_ID,});expect(plan.saveOperations.calendarEventsToUpdate).toHaveLength(1);@@ -192,13 +234,12 @@ describe('buildCalendarEventSaveOperations', () => {});it('updates the association only when the recurring event id changed', () => {- const plan = buildCalendarEventSaveOperations({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent({ recurringEventExternalId: 'recurring-id' }),],existingAssociations: [buildExistingAssociation()],existingCalendarEvents: [buildExistingCalendarEvent()],- calendarChannelId: CALENDAR_CHANNEL_ID,});expect(plan.saveOperations.calendarEventsToUpdate).toEqual([]);@@ -211,11 +252,10 @@ describe('buildCalendarEventSaveOperations', () => {});it('inserts events that have no existing association', () => {- const plan = buildCalendarEventSaveOperations({+ const plan = buildPlan({fetchedCalendarEvents: [buildFetchedCalendarEvent()],existingAssociations: [],existingCalendarEvents: [],- calendarChannelId: CALENDAR_CHANNEL_ID,});expect(plan.saveOperations.calendarEventsToInsert).toHaveLength(1);@@ -230,4 +270,39 @@ describe('buildCalendarEventSaveOperations', () => {expect(plan.existingCalendarEventIds).toEqual([]);expect(plan.participantsOfNewEvents).toHaveLength(1);});++ it('links an event stored by another channel instead of inserting a second one', () => {+ const plan = buildPlan({+ fetchedCalendarEvents: [buildFetchedCalendarEvent()],+ existingAssociations: [],+ existingCalendarEvents: [buildExistingCalendarEvent()],+ calendarEventIdToLinkByEventExternalId: new Map([+ ['external-event-id', CALENDAR_EVENT_ID],+ ]),+ otherCalendarChannels: [ATTENDEE_CHANNEL],+ });++ expect(plan.saveOperations).toEqual({+ calendarEventsToInsert: [],+ calendarEventsToUpdate: [],+ associationsToInsert: [+ {+ calendarEventId: CALENDAR_EVENT_ID,+ eventExternalId: 'external-event-id',+ calendarChannelId: CALENDAR_CHANNEL_ID,+ recurringEventExternalId: '',+ },+ ],+ associationsToUpdate: [],+ });+ expect(plan.existingCalendarEventIds).toEqual([]);+ expect(plan.participantsOfNewEvents).toEqual([]);+ expect(plan.participantsOfExistingEvents).toEqual([]);+ expect(plan.participantsOfLinkedEvents).toEqual([+ expect.objectContaining({+ handle: '[email protected]',+ calendarEventId: CALENDAR_EVENT_ID,+ }),+ ]);+ });});diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/build-fetched-calendar-event.test-util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/build-fetched-calendar-event.test-util.tsindex e557f189a21..8529c7c8ada 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/build-fetched-calendar-event.test-util.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/build-fetched-calendar-event.test-util.ts@@ -27,5 +27,6 @@ export const buildFetchedCalendarEvent = (},],status: 'confirmed',+ organizerHandle: '',...overrides,});diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/compute-calendar-event-sharing-key.util.spec.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/compute-calendar-event-sharing-key.util.spec.tsnew file mode 100644index 00000000000..8942ab88fd1--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/__tests__/compute-calendar-event-sharing-key.util.spec.ts@@ -0,0 +1,73 @@+import { ConnectedAccountProvider } from 'twenty-shared/types';++import { computeCalendarEventSharingKey } from 'src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-sharing-key.util';++describe('computeCalendarEventSharingKey', () => {+ it('keeps Google occurrences of one series apart even though they share an iCalUid', () => {+ expect(+ computeCalendarEventSharingKey({+ provider: ConnectedAccountProvider.GOOGLE,+ eventExternalId: 'series_20261012T090000Z',+ iCalUid: '[email protected]',+ }),+ ).not.toEqual(+ computeCalendarEventSharingKey({+ provider: ConnectedAccountProvider.GOOGLE,+ eventExternalId: 'series_20261019T090000Z',+ iCalUid: '[email protected]',+ }),+ );+ });++ it('keeps Google events apart when only their calendar-scoped ids collide', () => {+ expect(+ computeCalendarEventSharingKey({+ provider: ConnectedAccountProvider.GOOGLE,+ eventExternalId: 'event-id',+ iCalUid: '[email protected]',+ }),+ ).not.toEqual(+ computeCalendarEventSharingKey({+ provider: ConnectedAccountProvider.GOOGLE,+ eventExternalId: 'event-id',+ iCalUid: '[email protected]',+ }),+ );+ });++ it('matches Microsoft copies on the iCalUid since each mailbox has its own id', () => {+ expect(+ computeCalendarEventSharingKey({+ provider: ConnectedAccountProvider.MICROSOFT,+ eventExternalId: 'mailbox-a-event-id',+ iCalUid: 'meeting-ical-uid',+ }),+ ).toEqual(+ computeCalendarEventSharingKey({+ provider: ConnectedAccountProvider.MICROSOFT,+ eventExternalId: 'mailbox-b-event-id',+ iCalUid: 'meeting-ical-uid',+ }),+ );+ });++ it.each([+ { provider: ConnectedAccountProvider.GOOGLE, iCalUid: '' },+ { provider: ConnectedAccountProvider.MICROSOFT, iCalUid: null },+ {+ provider: ConnectedAccountProvider.IMAP_SMTP_CALDAV,+ iCalUid: 'meeting-ical-uid',+ },+ ])(+ 'never shares a $provider event with iCalUid "$iCalUid"',+ ({ provider, iCalUid }) => {+ expect(+ computeCalendarEventSharingKey({+ provider,+ eventExternalId: 'event-id',+ iCalUid,+ }),+ ).toBeUndefined();+ },+ );+});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.tsindex d9e71c9641b..76610bb9dc4 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@@ -1,8 +1,11 @@-import { isDefined } from 'twenty-shared/utils';+import { assertUnreachable, isDefined } from 'twenty-shared/utils';import { v4 as uuid } from 'uuid';+import { type CalendarEventChannelRole } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-channel-role.type';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 CalendarEventSharingChannel } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-sharing-channel.type';+import { computeCalendarEventChannelRole } from 'src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-channel-role.util';import {type ComparableCalendarEvent,hasCalendarEventChanged,@@ -16,11 +19,19 @@ export const buildCalendarEventSaveOperations = ({existingAssociations,existingCalendarEvents,calendarChannelId,+ channelHandles,+ calendarEventIdToLinkByEventExternalId,+ otherChannelIdsByCalendarEventId,+ otherCalendarChannels,}: {fetchedCalendarEvents: FetchedCalendarEvent[];existingAssociations: CalendarChannelEventAssociationWorkspaceEntity[];existingCalendarEvents: ComparableCalendarEvent[];calendarChannelId: string;+ channelHandles: string[];+ calendarEventIdToLinkByEventExternalId: Map<string, string>;+ otherChannelIdsByCalendarEventId: Map<string, string[]>;+ otherCalendarChannels: CalendarEventSharingChannel[];}): CalendarEventSavePlan => {const existingAssociationByEventExternalId = new Map(existingAssociations.map((association) => [@@ -34,6 +45,12 @@ export const buildCalendarEventSaveOperations = ({calendarEvent,]),);+ const calendarChannelById = new Map(+ otherCalendarChannels.map((calendarChannel) => [+ calendarChannel.id,+ calendarChannel,+ ]),+ );const saveOperations: CalendarEventSaveOperations = {calendarEventsToInsert: [],@@ -42,9 +59,15 @@ export const buildCalendarEventSaveOperations = ({associationsToUpdate: [],};const existingCalendarEventIds: string[] = [];+ const channelRoleByCalendarEventId = new Map<+ string,+ CalendarEventChannelRole+ >();const participantsOfNewEvents: FetchedParticipantWithCalendarEventId[] = [];const participantsOfExistingEvents: FetchedParticipantWithCalendarEventId[] =[];+ const participantsOfLinkedEvents: FetchedParticipantWithCalendarEventId[] =+ [];for (const fetchedCalendarEvent of fetchedCalendarEvents) {const {@@ -74,23 +97,73 @@ export const buildCalendarEventSaveOperations = ({const existingAssociation =existingAssociationByEventExternalId.get(eventExternalId);+ const calendarEventId =+ existingAssociation?.calendarEventId ??+ calendarEventIdToLinkByEventExternalId.get(eventExternalId);- if (isDefined(existingAssociation)) {- const { calendarEventId } = existingAssociation;- const existingCalendarEvent =- existingCalendarEventById.get(calendarEventId);+ if (!isDefined(calendarEventId)) {+ const newCalendarEventId = uuid();- existingCalendarEventIds.push(calendarEventId);+ channelRoleByCalendarEventId.set(newCalendarEventId, 'ONLY_CHANNEL');+ saveOperations.calendarEventsToInsert.push({+ id: newCalendarEventId,+ ...calendarEvent,+ });+ saveOperations.associationsToInsert.push({+ calendarEventId: newCalendarEventId,+ eventExternalId,+ calendarChannelId,+ recurringEventExternalId,+ });+ participantsOfNewEvents.push(+ ...participants.map((participant) => ({+ ...participant,+ calendarEventId: newCalendarEventId,+ })),+ );- if (- !isDefined(existingCalendarEvent) ||- hasCalendarEventChanged({ existingCalendarEvent, calendarEvent })- ) {- saveOperations.calendarEventsToUpdate.push({- criteria: calendarEventId,- partialEntity: calendarEvent,- });- }+ continue;+ }++ const existingCalendarEvent =+ existingCalendarEventById.get(calendarEventId);+ const channelRole = computeCalendarEventChannelRole({+ organizerHandle: fetchedCalendarEvent.organizerHandle,+ channelHandles,+ otherChannelIds:+ otherChannelIdsByCalendarEventId.get(calendarEventId) ?? [],+ calendarChannelById,+ });++ channelRoleByCalendarEventId.set(calendarEventId, channelRole);++ switch (channelRole) {+ case 'ONLY_CHANNEL':+ case 'ORGANIZER_CHANNEL':+ case 'ATTENDEE_CHANNEL':+ if (+ !isDefined(existingCalendarEvent) ||+ hasCalendarEventChanged({ existingCalendarEvent, calendarEvent })+ ) {+ saveOperations.calendarEventsToUpdate.push({+ criteria: calendarEventId,+ partialEntity: calendarEvent,+ });+ }+ break;+ case 'ATTENDEE_CHANNEL_WITH_ORGANIZER_SYNCING':+ break;+ default:+ assertUnreachable(channelRole);+ }++ const eventParticipants = participants.map((participant) => ({+ ...participant,+ calendarEventId,+ }));++ if (isDefined(existingAssociation)) {+ existingCalendarEventIds.push(calendarEventId);if (!isDefined(existingCalendarEvent) ||@@ -103,40 +176,26 @@ export const buildCalendarEventSaveOperations = ({});}- participantsOfExistingEvents.push(- ...participants.map((participant) => ({- ...participant,- calendarEventId,- })),- );+ participantsOfExistingEvents.push(...eventParticipants);continue;}- const calendarEventId = uuid();-- saveOperations.calendarEventsToInsert.push({- id: calendarEventId,- ...calendarEvent,- });saveOperations.associationsToInsert.push({calendarEventId,eventExternalId,calendarChannelId,recurringEventExternalId,});- participantsOfNewEvents.push(- ...participants.map((participant) => ({- ...participant,- calendarEventId,- })),- );+ participantsOfLinkedEvents.push(...eventParticipants);}return {saveOperations,existingCalendarEventIds,+ channelRoleByCalendarEventId,participantsOfNewEvents,participantsOfExistingEvents,+ participantsOfLinkedEvents,};};diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-channel-role.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-channel-role.util.tsnew file mode 100644index 00000000000..b01a17e7a9d--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-channel-role.util.ts@@ -0,0 +1,57 @@+import { CalendarChannelSyncStatus } from 'twenty-shared/types';+import { assertUnreachable, isDefined } from 'twenty-shared/utils';++import { type CalendarEventChannelRole } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-channel-role.type';+import { type CalendarEventSharingChannel } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-sharing-channel.type';+import { getCalendarChannelHandles } from 'src/modules/calendar/calendar-event-import-manager/utils/get-calendar-channel-handles.util';++export const computeCalendarEventChannelRole = ({+ organizerHandle,+ channelHandles,+ otherChannelIds,+ calendarChannelById,+}: {+ organizerHandle: string;+ channelHandles: string[];+ otherChannelIds: string[];+ calendarChannelById: Map<string, CalendarEventSharingChannel>;+}): CalendarEventChannelRole => {+ if (otherChannelIds.length === 0) {+ return 'ONLY_CHANNEL';+ }++ if (channelHandles.includes(organizerHandle)) {+ return 'ORGANIZER_CHANNEL';+ }++ const isOrganizerChannelSyncing = otherChannelIds.some((otherChannelId) => {+ const otherChannel = calendarChannelById.get(otherChannelId);++ if (+ !isDefined(otherChannel) ||+ !otherChannel.isSyncEnabled ||+ !getCalendarChannelHandles({+ calendarChannel: otherChannel,+ connectedAccount: otherChannel.connectedAccount,+ }).includes(organizerHandle)+ ) {+ return false;+ }++ switch (otherChannel.syncStatus) {+ case CalendarChannelSyncStatus.ACTIVE:+ case CalendarChannelSyncStatus.ONGOING:+ return true;+ case CalendarChannelSyncStatus.NOT_SYNCED:+ case CalendarChannelSyncStatus.FAILED_INSUFFICIENT_PERMISSIONS:+ case CalendarChannelSyncStatus.FAILED_UNKNOWN:+ return false;+ default:+ return assertUnreachable(otherChannel.syncStatus);+ }+ });++ return isOrganizerChannelSyncing+ ? 'ATTENDEE_CHANNEL_WITH_ORGANIZER_SYNCING'+ : 'ATTENDEE_CHANNEL';+};diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-sharing-key.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-sharing-key.util.tsnew file mode 100644index 00000000000..0709a43849d--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-sharing-key.util.ts@@ -0,0 +1,30 @@+import { isNonEmptyString } from '@sniptt/guards';+import { ConnectedAccountProvider } from 'twenty-shared/types';+import { assertUnreachable } from 'twenty-shared/utils';++export const computeCalendarEventSharingKey = ({+ provider,+ eventExternalId,+ iCalUid,+}: {+ provider: ConnectedAccountProvider;+ eventExternalId: string | null;+ iCalUid: string | null;+}): string | undefined => {+ switch (provider) {+ case ConnectedAccountProvider.GOOGLE:+ return isNonEmptyString(eventExternalId) && isNonEmptyString(iCalUid)+ ? JSON.stringify([eventExternalId, iCalUid])+ : undefined;+ case ConnectedAccountProvider.MICROSOFT:+ return isNonEmptyString(iCalUid) ? iCalUid : undefined;+ case ConnectedAccountProvider.IMAP_SMTP_CALDAV:+ case ConnectedAccountProvider.OIDC:+ case ConnectedAccountProvider.SAML:+ case ConnectedAccountProvider.EMAIL_GROUP:+ case ConnectedAccountProvider.APP:+ return undefined;+ default:+ return assertUnreachable(provider);+ }+};diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/get-calendar-channel-handles.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/get-calendar-channel-handles.util.tsnew file mode 100644index 00000000000..e84786bd7a1--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/get-calendar-channel-handles.util.ts@@ -0,0 +1,15 @@+import { isNonEmptyString } from '@sniptt/guards';++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';++export const getCalendarChannelHandles = ({+ calendarChannel,+ connectedAccount,+}: {+ calendarChannel: Pick<CalendarChannelEntity, 'handle'>;+ connectedAccount: Pick<ConnectedAccountEntity, 'handleAliases'>;+}): string[] =>+ [calendarChannel.handle, ...(connectedAccount.handleAliases ?? [])]+ .filter(isNonEmptyString)+ .map((handle) => handle.toLowerCase());diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/resolve-calendar-event-sharing.util.ts b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/resolve-calendar-event-sharing.util.tsnew file mode 100644index 00000000000..902bf08b925--- /dev/null+++ b/packages/twenty-server/src/modules/calendar/calendar-event-import-manager/utils/resolve-calendar-event-sharing.util.ts@@ -0,0 +1,92 @@+import { type ConnectedAccountProvider } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++import { computeCalendarEventSharingKey } from 'src/modules/calendar/calendar-event-import-manager/utils/compute-calendar-event-sharing-key.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';++type SharedAssociation = Pick<+ CalendarChannelEventAssociationWorkspaceEntity,+ 'calendarChannelId' | 'calendarEventId' | 'eventExternalId'+>;++export const resolveCalendarEventSharing = ({+ provider,+ fetchedCalendarEvents,+ existingEventExternalIds,+ sharedAssociations,+ iCalUidByCalendarEventId,+ isCalendarEventSharingEnabled,+}: {+ provider: ConnectedAccountProvider;+ fetchedCalendarEvents: FetchedCalendarEvent[];+ existingEventExternalIds: Set<string>;+ sharedAssociations: SharedAssociation[];+ iCalUidByCalendarEventId: Map<string, string | null>;+ isCalendarEventSharingEnabled: boolean;+}): {+ calendarEventIdToLinkByEventExternalId: Map<string, string>;+ otherChannelIdsByCalendarEventId: Map<string, string[]>;+} => {+ const otherChannelIdsByCalendarEventId = new Map<string, string[]>();+ const calendarEventIdBySharingKey = new Map<string, string>();++ for (const association of sharedAssociations) {+ const otherChannelIds =+ otherChannelIdsByCalendarEventId.get(association.calendarEventId) ?? [];++ if (!otherChannelIds.includes(association.calendarChannelId)) {+ otherChannelIdsByCalendarEventId.set(association.calendarEventId, [+ ...otherChannelIds,+ association.calendarChannelId,+ ]);+ }++ const sharingKey = computeCalendarEventSharingKey({+ provider,+ eventExternalId: association.eventExternalId,+ iCalUid:+ iCalUidByCalendarEventId.get(association.calendarEventId) ?? null,+ });++ if (isDefined(sharingKey) && !calendarEventIdBySharingKey.has(sharingKey)) {+ calendarEventIdBySharingKey.set(sharingKey, association.calendarEventId);+ }+ }++ const calendarEventIdToLinkByEventExternalId = new Map<string, string>();++ if (!isCalendarEventSharingEnabled) {+ return {+ calendarEventIdToLinkByEventExternalId,+ otherChannelIdsByCalendarEventId,+ };+ }++ for (const fetchedCalendarEvent of fetchedCalendarEvents) {+ if (existingEventExternalIds.has(fetchedCalendarEvent.id)) {+ continue;+ }++ const sharingKey = computeCalendarEventSharingKey({+ provider,+ eventExternalId: fetchedCalendarEvent.id,+ iCalUid: fetchedCalendarEvent.iCalUid,+ });+ const calendarEventId = isDefined(sharingKey)+ ? calendarEventIdBySharingKey.get(sharingKey)+ : undefined;++ if (isDefined(calendarEventId)) {+ calendarEventIdToLinkByEventExternalId.set(+ fetchedCalendarEvent.id,+ calendarEventId,+ );+ }+ }++ return {+ calendarEventIdToLinkByEventExternalId,+ otherChannelIdsByCalendarEventId,+ };+};diff --git a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.tsindex 0d196fb1e38..bd7ed8d1679 100644--- a/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts+++ b/packages/twenty-server/src/modules/calendar/calendar-event-participant-manager/services/calendar-event-participant.service.ts@@ -15,6 +15,7 @@ import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-systemimport { CALENDAR_EVENT_PARTICIPANT_CHUNK_SIZE } from 'src/modules/calendar/calendar-event-participant-manager/constants/calendar-event-participant-chunk-size';import { type CalendarEventParticipantSaveOperations } from 'src/modules/calendar/calendar-event-participant-manager/types/calendar-event-participant-save-operations.type';import { type CalendarEventParticipantWorkspaceEntity } from 'src/modules/calendar/common/standard-objects/calendar-event-participant.workspace-entity';+import { type FetchedCalendarEventParticipant } from 'src/modules/calendar/common/types/fetched-calendar-event.type';import {CreateCompanyAndContactJob,type CreateCompanyAndContactJobData,@@ -82,12 +83,14 @@ export class CalendarEventParticipantService {public async matchParticipantsAndEnqueueContactCreationJob({savedParticipantIds,+ participantsOfLinkedEvents,calendarChannel,connectedAccount,workspaceId,calendarEventIds,}: {savedParticipantIds: string[];+ participantsOfLinkedEvents: FetchedCalendarEventParticipant[];calendarChannel: CalendarChannelEntity;connectedAccount: ConnectedAccountEntity;workspaceId: string;@@ -123,7 +126,10 @@ export class CalendarEventParticipantService {{workspaceId,connectedAccount,- contactsToCreate: savedParticipants.map((participant) => ({+ contactsToCreate: [+ ...savedParticipants,+ ...participantsOfLinkedEvents,+ ].map((participant) => ({handle: participant.handle ?? '',displayName:participant.displayName ?? participant.handle ?? '',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.tsindex fb780f377ec..2ab70ed7048 100644--- 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@@ -1,8 +1,10 @@+import { type CalendarEventChannelRole } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-channel-role.type';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 CHANNEL_HANDLE = '[email protected]';const buildFetchedParticipant = (overrides: Partial<FetchedParticipantWithCalendarEventId> = {},@@ -30,12 +32,30 @@ const buildExistingParticipant = (...overrides,}) as CalendarEventParticipantWorkspaceEntity;+const buildOperations = ({+ fetchedParticipants,+ existingParticipants,+ shouldSkipUnchangedParticipants = true,+ channelRole = 'ONLY_CHANNEL',+}: {+ fetchedParticipants: FetchedParticipantWithCalendarEventId[];+ existingParticipants: CalendarEventParticipantWorkspaceEntity[];+ shouldSkipUnchangedParticipants?: boolean;+ channelRole?: CalendarEventChannelRole;+}) =>+ buildCalendarEventParticipantSaveOperations({+ fetchedParticipants,+ existingParticipants,+ shouldSkipUnchangedParticipants,+ channelRoleByCalendarEventId: new Map([[CALENDAR_EVENT_ID, channelRole]]),+ channelHandles: [CHANNEL_HANDLE],+ });+describe('buildCalendarEventParticipantSaveOperations', () => {it('skips existing participants whose fields did not change', () => {- const operations = buildCalendarEventParticipantSaveOperations({+ const operations = buildOperations({fetchedParticipants: [buildFetchedParticipant()],existingParticipants: [buildExistingParticipant()],- shouldSkipUnchangedParticipants: true,});expect(operations).toEqual({@@ -46,7 +66,7 @@ describe('buildCalendarEventParticipantSaveOperations', () => {});it('updates unchanged participants when skipping is disabled', () => {- const operations = buildCalendarEventParticipantSaveOperations({+ const operations = buildOperations({fetchedParticipants: [buildFetchedParticipant()],existingParticipants: [buildExistingParticipant()],shouldSkipUnchangedParticipants: false,@@ -61,10 +81,9 @@ describe('buildCalendarEventParticipantSaveOperations', () => {});it('treats a null persisted display name as equal to an empty fetched one', () => {- const operations = buildCalendarEventParticipantSaveOperations({+ const operations = buildOperations({fetchedParticipants: [buildFetchedParticipant({ displayName: '' })],existingParticipants: [buildExistingParticipant({ displayName: null })],- shouldSkipUnchangedParticipants: true,});expect(operations.participantsToUpdate).toEqual([]);@@ -77,10 +96,9 @@ describe('buildCalendarEventParticipantSaveOperations', () => {])('updates the participant when %s changed', (_, fetchedOverrides) => {const fetchedParticipant = buildFetchedParticipant(fetchedOverrides);- const operations = buildCalendarEventParticipantSaveOperations({+ const operations = buildOperations({fetchedParticipants: [fetchedParticipant],existingParticipants: [buildExistingParticipant()],- shouldSkipUnchangedParticipants: true,});expect(operations.participantsToUpdate).toEqual([@@ -93,15 +111,14 @@ describe('buildCalendarEventParticipantSaveOperations', () => {expect(operations.participantIdsToDelete).toEqual([]);});- it('inserts new participants and deletes missing ones', () => {+ it('inserts new participants and deletes missing ones when the event is only in this channel', () => {const newParticipant = buildFetchedParticipant({handle: '[email protected]',});- const operations = buildCalendarEventParticipantSaveOperations({+ const operations = buildOperations({fetchedParticipants: [newParticipant],existingParticipants: [buildExistingParticipant()],- shouldSkipUnchangedParticipants: true,});expect(operations.participantsToInsert).toEqual([@@ -112,4 +129,62 @@ describe('buildCalendarEventParticipantSaveOperations', () => {'existing-participant-id',]);});++ it.each<CalendarEventChannelRole>([+ 'ORGANIZER_CHANNEL',+ 'ATTENDEE_CHANNEL',+ 'ATTENDEE_CHANNEL_WITH_ORGANIZER_SYNCING',+ ])(+ 'never deletes the attendees a shared event lists elsewhere as %s',+ (channelRole) => {+ const operations = buildOperations({+ fetchedParticipants: [+ buildFetchedParticipant({ handle: '[email protected]' }),+ ],+ existingParticipants: [buildExistingParticipant()],+ channelRole,+ });++ expect(operations.participantsToInsert).toEqual([+ expect.objectContaining({ handle: '[email protected]' }),+ ]);+ expect(operations.participantIdsToDelete).toEqual([]);+ },+ );++ it.each<CalendarEventChannelRole>([+ 'ATTENDEE_CHANNEL',+ 'ATTENDEE_CHANNEL_WITH_ORGANIZER_SYNCING',+ ])(+ 'lets an %s update only the answer of its own attendee, even back to no answer',+ (channelRole) => {+ const operations = buildOperations({+ fetchedParticipants: [+ buildFetchedParticipant({ responseStatus: 'DECLINED' }),+ buildFetchedParticipant({+ handle: CHANNEL_HANDLE,+ responseStatus: 'NEEDS_ACTION',+ }),+ ],+ existingParticipants: [+ buildExistingParticipant(),+ buildExistingParticipant({+ id: 'channel-owner-participant-id',+ handle: CHANNEL_HANDLE,+ }),+ ],+ shouldSkipUnchangedParticipants: false,+ channelRole,+ });++ expect(operations.participantsToUpdate).toEqual([+ {+ criteria: 'channel-owner-participant-id',+ partialEntity: expect.objectContaining({+ responseStatus: 'NEEDS_ACTION',+ }),+ },+ ]);+ },+ );});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.tsindex b2bc7fa41f8..54f36cf1bb4 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@@ -1,6 +1,7 @@-import { isDefined } from 'twenty-shared/utils';+import { assertUnreachable, isDefined } from 'twenty-shared/utils';import { v4 as uuid } from 'uuid';+import { type CalendarEventChannelRole } from 'src/modules/calendar/calendar-event-import-manager/types/calendar-event-channel-role.type';import { type CalendarEventParticipantSaveOperations } from 'src/modules/calendar/calendar-event-participant-manager/types/calendar-event-participant-save-operations.type';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';@@ -30,10 +31,14 @@ export const buildCalendarEventParticipantSaveOperations = ({fetchedParticipants,existingParticipants,shouldSkipUnchangedParticipants,+ channelRoleByCalendarEventId,+ channelHandles,}: {fetchedParticipants: FetchedParticipantWithCalendarEventId[];existingParticipants: CalendarEventParticipantWorkspaceEntity[];shouldSkipUnchangedParticipants: boolean;+ channelRoleByCalendarEventId: Map<string, CalendarEventChannelRole>;+ channelHandles: string[];}): CalendarEventParticipantSaveOperations => {const existingParticipantByKey = new Map<string,@@ -77,6 +82,26 @@ export const buildCalendarEventParticipantSaveOperations = ({continue;}+ const channelRole = channelRoleByCalendarEventId.get(+ fetchedParticipant.calendarEventId,+ );++ switch (channelRole) {+ case 'ONLY_CHANNEL':+ case 'ORGANIZER_CHANNEL':+ break;+ case 'ATTENDEE_CHANNEL':+ case 'ATTENDEE_CHANNEL_WITH_ORGANIZER_SYNCING':+ if (!channelHandles.includes(fetchedParticipant.handle)) {+ continue;+ }+ break;+ case undefined:+ continue;+ default:+ assertUnreachable(channelRole);+ }+operations.participantsToUpdate.push({criteria: existingParticipant.id,partialEntity: fetchedParticipant,@@ -92,7 +117,22 @@ export const buildCalendarEventParticipantSaveOperations = ({continue;}- operations.participantIdsToDelete.push(existingParticipant.id);+ const channelRole = channelRoleByCalendarEventId.get(+ existingParticipant.calendarEventId,+ );++ switch (channelRole) {+ case 'ONLY_CHANNEL':+ operations.participantIdsToDelete.push(existingParticipant.id);+ break;+ case 'ORGANIZER_CHANNEL':+ case 'ATTENDEE_CHANNEL':+ case 'ATTENDEE_CHANNEL_WITH_ORGANIZER_SYNCING':+ case undefined:+ break;+ default:+ assertUnreachable(channelRole);+ }}return operations;diff --git a/packages/twenty-server/src/modules/calendar/common/types/fetched-calendar-event.type.ts b/packages/twenty-server/src/modules/calendar/common/types/fetched-calendar-event.type.tsindex d521d771681..5b4fd6d922f 100644--- a/packages/twenty-server/src/modules/calendar/common/types/fetched-calendar-event.type.ts+++ b/packages/twenty-server/src/modules/calendar/common/types/fetched-calendar-event.type.ts@@ -22,6 +22,7 @@ export type FetchedCalendarEvent = {externalUpdatedAt: string;conferenceSolution: string;recurringEventExternalId?: string;+ organizerHandle: string;participants: FetchedCalendarEventParticipant[];status: string;};diff --git a/packages/twenty-server/test/integration/google/calendar/event-sharing.integration-spec.ts b/packages/twenty-server/test/integration/google/calendar/event-sharing.integration-spec.tsnew file mode 100644index 00000000000..b62a546813b--- /dev/null+++ b/packages/twenty-server/test/integration/google/calendar/event-sharing.integration-spec.ts@@ -0,0 +1,172 @@+import { randomUUID } from 'node:crypto';++import { ConnectedAccountProvider } from 'twenty-shared/types';++import { googleCalendarEvent } from 'test/integration/google/mocks/google-calendar-event.util';+import { setupGoogleMock } from 'test/integration/google/mocks/setup-google-mock.util';+import { connectMessagingAccount } from 'test/integration/utils/connect-messaging-account.util';+import { findImportedCalendarEventTitles } from 'test/integration/utils/find-imported-records.util';+import { findRecordNodesByFilter } from 'test/integration/utils/find-records-by-filter.util';+import { runCalendarChannelEventsImport } from 'test/integration/utils/run-calendar-channel-events-import.util';+import { runCalendarChannelListFetch } from 'test/integration/utils/run-calendar-channel-list-fetch.util';++const HANDLE = '[email protected]';+const OTHER_HANDLE = '[email protected]';++const syncToken = () => `event-sharing-sync-token-${randomUUID()}`;++const runCalendarSync = async (calendarChannelId: string): Promise<void> => {+ await runCalendarChannelListFetch(calendarChannelId);+ await runCalendarChannelEventsImport(calendarChannelId);+};++const findAssociations = async (eventExternalIds: string[]) =>+ findRecordNodesByFilter<{+ calendarEventId: string;+ calendarChannelId: string;+ }>(+ 'calendarChannelEventAssociation',+ 'calendarChannelEventAssociations',+ 'calendarEventId calendarChannelId',+ { eventExternalId: { in: eventExternalIds } },+ );++const findAssociationChannelIds = async (+ eventExternalIds: string[],+): Promise<string[]> =>+ (await findAssociations(eventExternalIds))+ .map(({ calendarChannelId }) => calendarChannelId)+ .sort();++const findCalendarEventIds = async (+ eventExternalIds: string[],+): Promise<string[]> => [+ ...new Set(+ (await findAssociations(eventExternalIds)).map(+ ({ calendarEventId }) => calendarEventId,+ ),+ ),+];++const findParticipantResponseStatusByHandle = async (+ calendarEventId: string,+): Promise<Record<string, string>> => {+ const participants = await findRecordNodesByFilter<{+ handle: string;+ responseStatus: string;+ }>(+ 'calendarEventParticipant',+ 'calendarEventParticipants',+ 'handle responseStatus',+ { calendarEventId: { eq: calendarEventId } },+ );++ return Object.fromEntries(+ participants.map(({ handle, responseStatus }) => [handle, responseStatus]),+ );+};++const attendee = (email: string, responseStatus = 'accepted') => ({+ email,+ responseStatus,+});++describe('Google calendar event sharing (integration)', () => {+ const google = setupGoogleMock({ handle: HANDLE });++ let channel: Awaited<ReturnType<typeof connectMessagingAccount>>;+ let otherChannel: Awaited<ReturnType<typeof connectMessagingAccount>>;++ beforeAll(async () => {+ channel = await connectMessagingAccount({+ provider: ConnectedAccountProvider.GOOGLE,+ handle: HANDLE,+ });++ google.actAsAccount(OTHER_HANDLE);++ otherChannel = await connectMessagingAccount({+ provider: ConnectedAccountProvider.GOOGLE,+ handle: OTHER_HANDLE,+ });++ google.actAsAccount(HANDLE);+ }, 120000);++ afterAll(async () => {+ await otherChannel?.cleanup().catch(() => undefined);+ await channel?.cleanup().catch(() => undefined);+ });++ it('stores a meeting synced by two calendars once', async () => {+ const sharedExternalId = `google-calendar-event-${randomUUID()}`;+ const sharedTitle = `Shared meeting ${randomUUID()}`;++ google.serveCalendarEvents(+ [googleCalendarEvent({ id: sharedExternalId, summary: sharedTitle })],+ { nextSyncToken: syncToken() },+ );++ await runCalendarSync(channel.calendarChannelId);+ await runCalendarSync(otherChannel.calendarChannelId);++ expect(await findAssociationChannelIds([sharedExternalId])).toEqual(+ [channel.calendarChannelId, otherChannel.calendarChannelId].sort(),+ );+ expect(await findCalendarEventIds([sharedExternalId])).toHaveLength(1);+ expect(await findImportedCalendarEventTitles([sharedTitle])).toEqual([+ sharedTitle,+ ]);+ }, 120000);++ it('never lets a guest copy change the fields or another attendee answer while the organizer copy syncs', async () => {+ const sharedExternalId = `google-calendar-event-${randomUUID()}`;+ const guestHandle = `guest-${randomUUID()}@example.com`;+ const organizer = { email: OTHER_HANDLE };+ const organizerTitle = `Organizer title ${randomUUID()}`;+ const guestTitle = `Guest title ${randomUUID()}`;++ google.serveCalendarEvents(+ [+ googleCalendarEvent({+ id: sharedExternalId,+ summary: organizerTitle,+ organizer,+ attendees: [attendee(HANDLE), attendee(guestHandle)],+ }),+ ],+ { nextSyncToken: syncToken() },+ );++ await runCalendarSync(otherChannel.calendarChannelId);++ google.serveCalendarEvents(+ [+ googleCalendarEvent({+ id: sharedExternalId,+ summary: guestTitle,+ organizer,+ attendees: [+ attendee(HANDLE, 'tentative'),+ attendee(guestHandle, 'declined'),+ ],+ }),+ ],+ { nextSyncToken: syncToken() },+ );++ await runCalendarSync(channel.calendarChannelId);++ const [calendarEventId] = await findCalendarEventIds([sharedExternalId]);++ expect(+ await findImportedCalendarEventTitles([organizerTitle, guestTitle]),+ ).toEqual([organizerTitle]);+ expect(+ await findParticipantResponseStatusByHandle(calendarEventId),+ ).toEqual({+ [HANDLE]: 'TENTATIVE',+ [guestHandle]: 'ACCEPTED',+ });+ }, 120000);+});diff --git a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snapindex 43d55b325f8..e9ff757c890 100644--- a/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap+++ b/packages/twenty-shared/src/metadata/__tests__/__snapshots__/standardObjectUniversalIdentifiers.test.ts.snap@@ -737,6 +737,9 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e"calendarEventIdIndex": {"universalIdentifier": "47a3c8d2-9f14-4b6e-8c5d-1a2b3f4e5c69",},+ "eventExternalIdIndex": {+ "universalIdentifier": "b14d63d0-c1ab-470f-927d-9c0c05277caa",+ },},"universalIdentifier": "20202020-491b-4aaa-9825-afd1bae6ae00","views": {@@ -862,7 +865,11 @@ exports[`STANDARD_OBJECTS universal identifiers should never change without an e"universalIdentifier": "ace17dae-1488-50eb-849e-02f409627627",},},- "indexes": {},+ "indexes": {+ "iCalUidIndex": {+ "universalIdentifier": "e38d1418-f994-4f0d-b0cd-41d4da240ea0",+ },+ },"universalIdentifier": "20202020-8f1d-4eef-9f85-0d1965e27221","views": {"allCalendarEvents": {diff --git a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts b/packages/twenty-shared/src/metadata/constants/standard-object.constant.tsindex 9d3d0856bc6..5fdcf0c398c 100644--- a/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts+++ b/packages/twenty-shared/src/metadata/constants/standard-object.constant.ts@@ -106,6 +106,9 @@ export const STANDARD_OBJECTS = {calendarEventIdIndex: {universalIdentifier: '47a3c8d2-9f14-4b6e-8c5d-1a2b3f4e5c69',},+ eventExternalIdIndex: {+ universalIdentifier: 'b14d63d0-c1ab-470f-927d-9c0c05277caa',+ },},views: {allCalendarChannelEventAssociations: buildStandardObjectIndexView({@@ -195,7 +198,11 @@ export const STANDARD_OBJECTS = {calendarEvent: {universalIdentifier: STANDARD_OBJECT_UNIVERSAL_IDENTIFIERS.calendarEvent,fields: STANDARD_OBJECT_FIELDS.calendarEvent,- indexes: {},+ indexes: {+ iCalUidIndex: {+ universalIdentifier: 'e38d1418-f994-4f0d-b0cd-41d4da240ea0',+ },+ },views: {allCalendarEvents: buildStandardObjectIndexView({objectUniversalIdentifier:diff --git a/packages/twenty-shared/src/types/FeatureFlagKey.ts b/packages/twenty-shared/src/types/FeatureFlagKey.tsindex c23451e0eb3..ee360ac71f9 100644--- a/packages/twenty-shared/src/types/FeatureFlagKey.ts+++ b/packages/twenty-shared/src/types/FeatureFlagKey.ts@@ -10,6 +10,7 @@ export enum FeatureFlagKey {IS_LOGS_SETTINGS_SECTION_ENABLED = 'IS_LOGS_SETTINGS_SECTION_ENABLED',IS_RECORD_LEVEL_SHARING_ENABLED = 'IS_RECORD_LEVEL_SHARING_ENABLED',IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED = 'IS_CALENDAR_SYNC_SKIP_UNCHANGED_RECORDS_ENABLED',+ IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED = 'IS_CALENDAR_EVENT_SHARED_ACROSS_CHANNELS_ENABLED',IS_RECORD_SHARE_VISIBILITY_GATING_ENABLED = 'IS_RECORD_SHARE_VISIBILITY_GATING_ENABLED',IS_AI_CHAT_INBOX_ENABLED = 'IS_AI_CHAT_INBOX_ENABLED',IS_APP_PREFERENCES_ENABLED = 'IS_APP_PREFERENCES_ENABLED',