Skip to content

The open alternative to Salesforce, designed for AI.

Send record events to application workflows without their related records (#28013)

Thomas Trompette27aff2712a19
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-upgrade-version-command.module.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-upgrade-version-command.module.ts
index f6f8640c4a6..43cbd6ed12f 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-upgrade-version-command.module.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-upgrade-version-command.module.ts
@@ -8,6 +8,7 @@ import { RenameDevelopersSettingsCommandMenuItemCommand } from 'src/database/com
import { BackfillMorphRelationHeadsCommand } from 'src/database/commands/upgrade-version-command/2-48/2-48-workspace-command-1791998420300-backfill-morph-relation-heads.command';
import { RemoveWorkflowRunIndexWorkflowVersionColumnCommand } from 'src/database/commands/upgrade-version-command/2-48/2-48-workspace-command-1792051845780-remove-workflow-run-index-workflow-version-column.command';
import { SyncCampaignComposerStandardMetadataCommand } from 'src/database/commands/upgrade-version-command/2-48/2-48-workspace-command-1792064982496-sync-campaign-composer-standard-metadata.command';
+import { FlushWorkflowAutomatedTriggerMapsCommand } from 'src/database/commands/upgrade-version-command/2-48/2-48-workspace-command-1792068879353-flush-workflow-automated-trigger-maps.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';
@@ -27,6 +28,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
BackfillMorphRelationHeadsCommand,
RemoveWorkflowRunIndexWorkflowVersionColumnCommand,
SyncCampaignComposerStandardMetadataCommand,
+ FlushWorkflowAutomatedTriggerMapsCommand,
],
})
export class V2_48_UpgradeVersionCommandModule {}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-workspace-command-1792068879353-flush-workflow-automated-trigger-maps.command.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-workspace-command-1792068879353-flush-workflow-automated-trigger-maps.command.ts
new file mode 100644
index 00000000000..431a5488aea
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-workspace-command-1792068879353-flush-workflow-automated-trigger-maps.command.ts
@@ -0,0 +1,51 @@
+import { Command } from 'nest-commander';
+
+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 { RegisteredWorkspaceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-workspace-command.decorator';
+import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+
+@RegisteredWorkspaceCommand('2.48.0', 1792068879353)
+@Command({
+ name: 'upgrade:2-48:flush-workflow-automated-trigger-maps',
+ description:
+ 'Flush the cached workflow automated triggers so they are rebuilt with their application',
+})
+export class FlushWorkflowAutomatedTriggerMapsCommand extends ProvisionedWorkspaceCommandRunner {
+ constructor(
+ protected readonly workspaceIteratorService: WorkspaceIteratorService,
+ private readonly workspaceCacheService: WorkspaceCacheService,
+ ) {
+ super(workspaceIteratorService);
+ }
+
+ override async runOnWorkspace(args: RunOnWorkspaceArgs): Promise<void> {
+ await this.up(args);
+ }
+
+ async up({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {
+ await this.flushWorkflowAutomatedTriggerMaps({ workspaceId, options });
+ }
+
+ async down({ workspaceId, options }: RunOnWorkspaceArgs): Promise<void> {
+ await this.flushWorkflowAutomatedTriggerMaps({ workspaceId, options });
+ }
+
+ private async flushWorkflowAutomatedTriggerMaps({
+ workspaceId,
+ options,
+ }: Pick<RunOnWorkspaceArgs, 'workspaceId' | 'options'>): Promise<void> {
+ this.logger.log(
+ `${options.dryRun ? '[DRY RUN] ' : ''}Workspace ${workspaceId}: flushing the cached workflow automated triggers`,
+ );
+
+ if (options.dryRun) {
+ return;
+ }
+
+ await this.workspaceCacheService.flush(workspaceId, [
+ 'workflowAutomatedTriggerMaps',
+ ]);
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/application.service.ts b/packages/twenty-server/src/engine/core-modules/application/application.service.ts
index 794fb4ba27a..dd39b231804 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application.service.ts
@@ -104,7 +104,7 @@ export class ApplicationService {
workspace?: never;
}
| {
- workspace: WorkspaceEntity;
+ workspace: Pick<WorkspaceEntity, 'id' | 'workspaceCustomApplicationId'>;
workspaceId?: never;
}) {
const workspace = isDefined(workspaceInput)
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/types/workflow-automated-trigger-maps.type.ts b/packages/twenty-server/src/engine/core-modules/workflow/types/workflow-automated-trigger-maps.type.ts
index 75905955bf4..8d8041323ee 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/types/workflow-automated-trigger-maps.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/types/workflow-automated-trigger-maps.type.ts
@@ -11,6 +11,7 @@ export type CoreDispatchIds =
export type CachedWorkflowAutomatedTrigger = {
workflowId: string;
legacyWorkflowId?: string;
+ applicationId: string;
type: AutomatedTriggerType;
settings: AutomatedTriggerSettings;
} & CoreDispatchIds;
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/compute-automated-trigger-from-workflow-version.util.spec.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/compute-automated-trigger-from-workflow-version.util.spec.ts
index 1f8d9d96461..209ec7fa79e 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/compute-automated-trigger-from-workflow-version.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/__tests__/compute-automated-trigger-from-workflow-version.util.spec.ts
@@ -9,6 +9,7 @@ const buildWorkflowVersion = (trigger: WorkflowTrigger | null) => ({
id: 'core-version-1',
workflowId: 'workspace-workflow-1',
coreWorkflowId: 'core-workflow-1',
+ applicationId: 'application-1',
triggers: trigger ? [trigger] : [],
});
@@ -28,6 +29,7 @@ describe('computeAutomatedTriggerFromWorkflowVersion', () => {
).toEqual({
workflowId: 'core-workflow-1',
legacyWorkflowId: 'workspace-workflow-1',
+ applicationId: 'application-1',
coreWorkflowVersionId: 'core-version-1',
workspaceWorkflowVersionId: 'workspace-version-1',
type: AutomatedTriggerType.DATABASE_EVENT,
diff --git a/packages/twenty-server/src/engine/core-modules/workflow/utils/compute-automated-trigger-from-workflow-version.util.ts b/packages/twenty-server/src/engine/core-modules/workflow/utils/compute-automated-trigger-from-workflow-version.util.ts
index 388907154d5..000870592f5 100644
--- a/packages/twenty-server/src/engine/core-modules/workflow/utils/compute-automated-trigger-from-workflow-version.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/workflow/utils/compute-automated-trigger-from-workflow-version.util.ts
@@ -12,7 +12,7 @@ export const computeAutomatedTriggerFromWorkflowVersion = ({
}: {
workflowVersion: Pick<
WorkflowVersionEntity,
- 'id' | 'workflowId' | 'coreWorkflowId' | 'triggers'
+ 'id' | 'workflowId' | 'coreWorkflowId' | 'applicationId' | 'triggers'
>;
workspaceWorkflowVersionId: string | null;
}): CachedWorkflowAutomatedTrigger | null => {
@@ -27,6 +27,7 @@ export const computeAutomatedTriggerFromWorkflowVersion = ({
return {
workflowId: workflowVersion.coreWorkflowId,
legacyWorkflowId: workflowVersion.workflowId ?? undefined,
+ applicationId: workflowVersion.applicationId,
...buildCoreDispatchIds({
coreWorkflowVersionId: workflowVersion.id,
workspaceWorkflowVersionId,
@@ -38,6 +39,7 @@ export const computeAutomatedTriggerFromWorkflowVersion = ({
return {
workflowId: workflowVersion.coreWorkflowId,
legacyWorkflowId: workflowVersion.workflowId ?? undefined,
+ applicationId: workflowVersion.applicationId,
...buildCoreDispatchIds({
coreWorkflowVersionId: workflowVersion.id,
workspaceWorkflowVersionId,
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.module.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.module.ts
index e421a94bc18..1823117c1fd 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.module.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.module.ts
@@ -4,6 +4,8 @@ import { Module } from '@nestjs/common';
import { WorkflowCoreModule } from 'src/engine/core-modules/workflow/workflow-core.module';
import { TypeOrmModule } from '@nestjs/typeorm';
+import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
+import { CoreEntityCacheModule } from 'src/engine/core-entity-cache/core-entity-cache.module';
import { CronModule } from 'src/engine/core-modules/cron/cron.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { RecordShareModule } from 'src/engine/core-modules/record-share/record-share.module';
@@ -15,6 +17,8 @@ import { WorkflowDatabaseEventTriggerListener } from 'src/modules/workflow/workf
@Module({
imports: [
+ ApplicationModule,
+ CoreEntityCacheModule,
WorkflowVersionCoreModule,
WorkflowCoreModule,
TypeOrmModule.forFeature([WorkspaceEntity]),
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/__tests__/workflow-database-event-trigger.listener.spec.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/__tests__/workflow-database-event-trigger.listener.spec.ts
index fbc00b672fb..f2d27ae7dbd 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/__tests__/workflow-database-event-trigger.listener.spec.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/__tests__/workflow-database-event-trigger.listener.spec.ts
@@ -3,16 +3,23 @@ import { Test, type TestingModule } from '@nestjs/testing';
import { TWENTY_STANDARD_APPLICATION_UNIVERSAL_IDENTIFIER } from 'twenty-shared/application';
import type { ObjectRecordUpdateEvent } from 'twenty-shared/database-events';
import {
+ FieldMetadataType,
MetadataReadability,
RecordShareAccessLevel,
RecordSharePrincipalType,
RecordShareRowCause,
+ RelationType,
} from 'twenty-shared/types';
+import { CoreEntityCacheService } from 'src/engine/core-entity-cache/services/core-entity-cache.service';
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { AutomatedTriggerType } from 'src/engine/core-modules/workflow/enums/automated-trigger-type.enum';
import { type FlatObjectMetadata } from 'src/engine/metadata-modules/flat-object-metadata/types/flat-object-metadata.type';
import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
+import { addFlatEntityToFlatEntityMapsOrThrow } from 'src/engine/metadata-modules/flat-entity/utils/add-flat-entity-to-flat-entity-maps-or-throw.util';
+import { getFlatFieldMetadataMock } from 'src/engine/metadata-modules/flat-field-metadata/__mocks__/get-flat-field-metadata.mock';
+import { getFlatObjectMetadataMock } from 'src/engine/metadata-modules/flat-object-metadata/__mocks__/get-flat-object-metadata.mock';
import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/services/record-access-policy.service';
import { RecordShareStorageService } from 'src/engine/core-modules/record-share/services/record-share-storage.service';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
@@ -22,27 +29,37 @@ import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/work
import { WorkflowDatabaseEventTriggerListener } from 'src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener';
import { WorkflowTriggerJob } from 'src/modules/workflow/workflow-trigger/jobs/workflow-trigger.job';
+const TWENTY_STANDARD_APPLICATION_ID = 'twenty-standard-application-id';
+const WORKSPACE_CUSTOM_APPLICATION_ID = 'workspace-custom-application-id';
+
describe('WorkflowDatabaseEventTriggerListener', () => {
let listener: WorkflowDatabaseEventTriggerListener;
let workspaceOrmManager: jest.Mocked<WorkspaceOrmManager>;
let messageQueueService: jest.Mocked<MessageQueueService>;
let workspaceCacheService: jest.Mocked<WorkspaceCacheService>;
let recordShareStorageService: jest.Mocked<RecordShareStorageService>;
+ let workflowCommonWorkspaceService: {
+ getWorkflowById: jest.Mock;
+ getObjectMetadataInfo: jest.Mock;
+ };
+ let findRelatedRecords: jest.Mock;
const setTriggerMap = (
- listeners: Array<{ workflowId: string; settings: object; type?: unknown }>,
+ listeners: Array<{
+ workflowId: string;
+ settings: object;
+ type?: unknown;
+ applicationId?: string;
+ }>,
{
applicationVersion = '1.0.1',
- isWorkflowCached = true,
- installedApplicationRole,
+ applicationRole,
}: {
applicationVersion?: string | null;
- isWorkflowCached?: boolean;
- installedApplicationRole?: { canReadObjectRecords: boolean } | null;
+ applicationRole?: { canReadObjectRecords: boolean } | null;
} = {},
) => {
- const cachedListeners = isWorkflowCached ? listeners : [];
- const isInstalledApplication = installedApplicationRole !== undefined;
+ const isApplicationWorkflow = applicationRole !== undefined;
workspaceCacheService.getOrRecompute.mockResolvedValue({
flatObjectMetadataMaps: { byUniversalIdentifier: {} },
@@ -52,22 +69,19 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
'application-id': {
id: 'application-id',
version: applicationVersion,
- canBeUninstalled: isInstalledApplication,
- defaultRoleId: installedApplicationRole
- ? 'application-role-id'
- : null,
+ defaultRoleId: applicationRole ? 'application-role-id' : null,
},
},
idByUniversalIdentifier: {},
},
- ...(isInstalledApplication
+ ...(isApplicationWorkflow
? {
- rolesPermissions: installedApplicationRole
+ rolesPermissions: applicationRole
? {
'application-role-id': {
'test-object-metadata': {
canReadObjectRecords:
- installedApplicationRole.canReadObjectRecords,
+ applicationRole.canReadObjectRecords,
canUpdateObjectRecords: false,
canSoftDeleteObjectRecords: false,
canDestroyObjectRecords: false,
@@ -85,21 +99,6 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
flatFieldMetadataMaps: createEmptyFlatEntityMaps(),
}
: {}),
- flatWorkflowMaps: {
- byUniversalIdentifier: Object.fromEntries(
- cachedListeners.map((listener) => [
- listener.workflowId,
- { id: listener.workflowId, applicationId: 'application-id' },
- ]),
- ),
- universalIdentifierById: Object.fromEntries(
- cachedListeners.map((listener) => [
- listener.workflowId,
- listener.workflowId,
- ]),
- ),
- universalIdentifiersByApplicationId: {},
- },
flatRoleMaps: { byUniversalIdentifier: {} },
workflowAutomatedTriggerMaps: {
byWorkflowId: Object.fromEntries(
@@ -109,6 +108,9 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
type: AutomatedTriggerType.DATABASE_EVENT,
coreWorkflowVersionId: `core-version-${listener.workflowId}`,
workspaceWorkflowVersionId: `workspace-version-${listener.workflowId}`,
+ applicationId: isApplicationWorkflow
+ ? 'application-id'
+ : WORKSPACE_CUSTOM_APPLICATION_ID,
...listener,
},
]),
@@ -147,8 +149,9 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
}) as FlatObjectMetadata;
beforeEach(async () => {
+ findRelatedRecords = jest.fn();
workspaceOrmManager = {
- getRepository: jest.fn().mockReturnValue({ find: jest.fn() }),
+ getRepository: jest.fn().mockReturnValue({ find: findRelatedRecords }),
executeInWorkspaceContext: jest
.fn()
.mockImplementation((fn: () => any, _authContext?: any) => fn()),
@@ -172,6 +175,15 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
findByRecordIds: jest.fn().mockResolvedValue([]),
} as unknown as jest.Mocked<RecordShareStorageService>;
+ workflowCommonWorkspaceService = {
+ getWorkflowById: jest.fn(),
+ getObjectMetadataInfo: jest.fn().mockResolvedValue({
+ flatObjectMetadata: createMockFlatObjectMetadata({}),
+ flatObjectMetadataMaps: { byId: {}, byName: {} },
+ flatFieldMetadataMaps: { byId: {}, byName: {} },
+ }),
+ };
+
const module: TestingModule = await Test.createTestingModule({
providers: [
WorkflowDatabaseEventTriggerListener,
@@ -199,15 +211,32 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
},
{
provide: WorkflowCommonWorkspaceService,
+ useValue: workflowCommonWorkspaceService,
+ },
+ {
+ provide: CoreEntityCacheService,
useValue: {
- getWorkflowById: jest.fn(),
- getObjectMetadataInfo: jest.fn().mockResolvedValue({
- flatObjectMetadata: createMockFlatObjectMetadata({}),
- flatObjectMetadataMaps: { byId: {}, byName: {} },
- flatFieldMetadataMaps: { byId: {}, byName: {} },
+ get: jest.fn().mockResolvedValue({
+ id: 'test-workspace',
+ workspaceCustomApplicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
}),
},
},
+ {
+ provide: ApplicationService,
+ useValue: {
+ findWorkspaceTwentyStandardAndCustomApplicationOrThrow: jest
+ .fn()
+ .mockResolvedValue({
+ twentyStandardFlatApplication: {
+ id: TWENTY_STANDARD_APPLICATION_ID,
+ },
+ workspaceCustomFlatApplication: {
+ id: WORKSPACE_CUSTOM_APPLICATION_ID,
+ },
+ }),
+ },
+ },
],
}).compile();
@@ -267,7 +296,10 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
});
it('should not trigger workflow while its application is still installing', async () => {
- setTriggerMap(mockEventListeners, { applicationVersion: null });
+ setTriggerMap(mockEventListeners, {
+ applicationVersion: null,
+ applicationRole: { canReadObjectRecords: true },
+ });
await listener.handleObjectRecordUpdateEvent(mockPayload);
@@ -276,7 +308,7 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
it('should trigger an application workflow on records its application role reads', async () => {
setTriggerMap(mockEventListeners, {
- installedApplicationRole: { canReadObjectRecords: true },
+ applicationRole: { canReadObjectRecords: true },
});
await listener.handleObjectRecordUpdateEvent(mockPayload);
@@ -286,7 +318,7 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
it('should not trigger an application workflow on records its application role cannot read', async () => {
setTriggerMap(mockEventListeners, {
- installedApplicationRole: { canReadObjectRecords: false },
+ applicationRole: { canReadObjectRecords: false },
});
await listener.handleObjectRecordUpdateEvent(mockPayload);
@@ -295,22 +327,22 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
});
it('should not trigger an application workflow whose application has no role', async () => {
- setTriggerMap(mockEventListeners, { installedApplicationRole: null });
+ setTriggerMap(mockEventListeners, { applicationRole: null });
await listener.handleObjectRecordUpdateEvent(mockPayload);
expect(messageQueueService.add).not.toHaveBeenCalled();
});
- it('should trigger workflow missing from the workflow cache', async () => {
- setTriggerMap(mockEventListeners, {
- applicationVersion: null,
- isWorkflowCached: false,
- });
+ it('should not trigger a workflow whose application is no longer installed', async () => {
+ setTriggerMap(
+ [{ ...mockEventListeners[0], applicationId: 'removed-application-id' }],
+ { applicationRole: { canReadObjectRecords: true } },
+ );
await listener.handleObjectRecordUpdateEvent(mockPayload);
- expect(messageQueueService.add).toHaveBeenCalledTimes(1);
+ expect(messageQueueService.add).not.toHaveBeenCalled();
});
it('should trigger workflow when no fields are specified', async () => {
@@ -400,6 +432,136 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
);
});
+ describe('with a record related to a company', () => {
+ const company = { id: 'company-id', name: 'Acme' };
+ const createdRecord = {
+ id: 'test-record',
+ field1: 'new',
+ companyId: company.id,
+ };
+ const createPayload: WorkspaceEventBatch<any> = {
+ ...mockPayload,
+ name: 'createEvent',
+ events: [
+ {
+ ...mockPayload.events[0],
+ properties: { after: createdRecord },
+ },
+ ],
+ };
+ const createListener = {
+ type: AutomatedTriggerType.DATABASE_EVENT,
+ workflowId,
+ settings: { eventName: 'createEvent' },
+ };
+
+ const expectEnqueuedRecord = ({
+ enqueuedWorkflowId = workflowId,
+ record,
+ }: {
+ enqueuedWorkflowId?: string;
+ record: object;
+ }) =>
+ expect(messageQueueService.add).toHaveBeenCalledWith(
+ WorkflowTriggerJob.name,
+ {
+ workspaceId,
+ workflowId: enqueuedWorkflowId,
+ coreWorkflowVersionId: `core-version-${enqueuedWorkflowId}`,
+ workspaceWorkflowVersionId: `workspace-version-${enqueuedWorkflowId}`,
+ payload: {
+ ...createPayload.events[0],
+ properties: { after: record },
+ },
+ },
+ { retryLimit: 3 },
+ );
+
+ beforeEach(() => {
+ const companyField = getFlatFieldMetadataMock({
+ id: 'company-field-id',
+ universalIdentifier: 'company-field-id',
+ objectMetadataId: 'test-object-metadata',
+ type: FieldMetadataType.RELATION,
+ name: 'company',
+ settings: {
+ relationType: RelationType.MANY_TO_ONE,
+ joinColumnName: 'companyId',
+ },
+ relationTargetObjectMetadataId: 'company-object-id',
+ });
+
+ workflowCommonWorkspaceService.getObjectMetadataInfo.mockResolvedValue({
+ flatObjectMetadata: createMockFlatObjectMetadata({
+ fieldIds: [companyField.id],
+ }),
+ flatObjectMetadataMaps: addFlatEntityToFlatEntityMapsOrThrow({
+ flatEntity: getFlatObjectMetadataMock({
+ id: 'company-object-id',
+ universalIdentifier: 'company-object-id',
+ nameSingular: 'company',
+ }),
+ flatEntityMaps: createEmptyFlatEntityMaps(),
+ }),
+ flatFieldMetadataMaps: addFlatEntityToFlatEntityMapsOrThrow({
+ flatEntity: companyField,
+ flatEntityMaps: createEmptyFlatEntityMaps(),
+ }),
+ });
+ findRelatedRecords.mockResolvedValue([company]);
+ });
+
+ it('should give a workspace workflow the related company', async () => {
+ setTriggerMap([createListener]);
+
+ await listener.handleObjectRecordCreateEvent(createPayload);
+
+ expect(messageQueueService.add).toHaveBeenCalledTimes(1);
+ expectEnqueuedRecord({ record: { ...createdRecord, company } });
+ });
+
+ it('should not give an application workflow the related company', async () => {
+ setTriggerMap([createListener], {
+ applicationRole: { canReadObjectRecords: true },
+ });
+
+ await listener.handleObjectRecordCreateEvent(createPayload);
+
+ expect(messageQueueService.add).toHaveBeenCalledTimes(1);
+ expectEnqueuedRecord({ record: createdRecord });
+ expect(findRelatedRecords).not.toHaveBeenCalled();
+ });
+
+ it('should give the related company only to the workspace workflow when an application workflow listens too', async () => {
+ const workspaceWorkflowId = 'workspace-workflow';
+ const applicationWorkflowId = 'application-workflow';
+
+ setTriggerMap(
+ [
+ {
+ ...createListener,
+ workflowId: workspaceWorkflowId,
+ applicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
+ },
+ { ...createListener, workflowId: applicationWorkflowId },
+ ],
+ { applicationRole: { canReadObjectRecords: true } },
+ );
+
+ await listener.handleObjectRecordCreateEvent(createPayload);
+
+ expect(messageQueueService.add).toHaveBeenCalledTimes(2);
+ expectEnqueuedRecord({
+ enqueuedWorkflowId: workspaceWorkflowId,
+ record: { ...createdRecord, company },
+ });
+ expectEnqueuedRecord({
+ enqueuedWorkflowId: applicationWorkflowId,
+ record: createdRecord,
+ });
+ });
+ });
+
it('should handle delete events correctly', async () => {
const deletePayload: WorkspaceEventBatch<any> = {
...mockPayload,
@@ -519,7 +681,7 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
it('should only trigger workflow for records of a private object shared with the workflow role', async () => {
const applicationRoleId = 'application-role-id';
- const applicationId = 'twenty-standard-application-id';
+ const applicationId = TWENTY_STANDARD_APPLICATION_ID;
const privatePayload: WorkspaceEventBatch<ObjectRecordUpdateEvent> = {
...mockPayload,
@@ -564,7 +726,6 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
}
: {
flatApplicationMaps: { byId: {}, idByUniversalIdentifier: {} },
- flatWorkflowMaps: createEmptyFlatEntityMaps(),
workflowAutomatedTriggerMaps: {
byWorkflowId: {
[workflowId]: {
@@ -572,6 +733,7 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
coreWorkflowVersionId: `core-version-${workflowId}`,
workspaceWorkflowVersionId: `workspace-version-${workflowId}`,
workflowId,
+ applicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
settings: { eventName: databaseEventName },
},
},
@@ -639,7 +801,6 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
}
: {
flatApplicationMaps: { byId: {}, idByUniversalIdentifier: {} },
- flatWorkflowMaps: createEmptyFlatEntityMaps(),
workflowAutomatedTriggerMaps: {
byWorkflowId: {
[workflowId]: {
@@ -647,6 +808,7 @@ describe('WorkflowDatabaseEventTriggerListener', () => {
coreWorkflowVersionId: `core-version-${workflowId}`,
workspaceWorkflowVersionId: `workspace-version-${workflowId}`,
workflowId,
+ applicationId: WORKSPACE_CUSTOM_APPLICATION_ID,
settings: { eventName: databaseEventName },
},
},
diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
index 45be29a0a2b..0cfac6b981b 100644
--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/automated-trigger/listeners/workflow-database-event-trigger.listener.ts
@@ -29,7 +29,8 @@ import { RecordAccessPolicyService } from 'src/engine/core-modules/record-share/
import { omitInheritedReadabilityChildRecords } from 'src/engine/core-modules/record-share/utils/omit-inherited-readability-child-records.util';
import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';
import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';
-import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
+import { ApplicationService } from 'src/engine/core-modules/application/application.service';
+import { CoreEntityCacheService } from 'src/engine/core-entity-cache/services/core-entity-cache.service';
import { findActiveFlatApplicationById } from 'src/engine/core-modules/application/utils/find-active-flat-application-by-id.util';
import { isApplicationInstallPending } from 'src/engine/core-modules/application/utils/is-application-install-pending.util';
import { isCachedDatabaseEventTrigger } from 'src/engine/core-modules/workflow/utils/cached-workflow-automated-trigger.util';
@@ -53,8 +54,8 @@ import {
type DatabaseEventTriggerListener = {
workflowId: string;
legacyWorkflowId?: string;
+ applicationId: string;
settings: AutomatedTriggerSettings;
- installedApplication?: FlatApplication;
} & CoreDispatchIds;
type TriggerEvaluationArgs = {
@@ -76,6 +77,8 @@ export class WorkflowDatabaseEventTriggerListener {
private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly recordAccessPolicyService: RecordAccessPolicyService,
+ private readonly applicationService: ApplicationService,
+ private readonly coreEntityCacheService: CoreEntityCacheService,
) {}
@OnDatabaseBatchEvent('*', DatabaseEventAction.CREATED)
@@ -86,12 +89,11 @@ export class WorkflowDatabaseEventTriggerListener {
return;
}
- const clonedPayload = structuredClone(payload);
-
- await this.enrichCreatedEvent(clonedPayload);
await this.handleEvent({
- payload: clonedPayload,
+ payload,
action: DatabaseEventAction.CREATED,
+ enrichPayload: (payloadToEnrich) =>
+ this.enrichCreatedEvent(payloadToEnrich),
});
}
@@ -103,13 +105,11 @@ export class WorkflowDatabaseEventTriggerListener {
return;
}
- const clonedPayload = structuredClone(payload);
-
- await this.enrichUpdatedEvent(clonedPayload);
-
await this.handleEvent({
- payload: clonedPayload,
+ payload,
action: DatabaseEventAction.UPDATED,
+ enrichPayload: (payloadToEnrich) =>
+ this.enrichUpdatedEvent(payloadToEnrich),
});
}
@@ -121,12 +121,11 @@ export class WorkflowDatabaseEventTriggerListener {
return;
}
- const clonedPayload = structuredClone(payload);
-
- await this.enrichDeletedEvent(clonedPayload);
await this.handleEvent({
- payload: clonedPayload,
+ payload,
action: DatabaseEventAction.DELETED,
+ enrichPayload: (payloadToEnrich) =>
+ this.enrichDeletedEvent(payloadToEnrich),
});
}
@@ -138,12 +137,11 @@ export class WorkflowDatabaseEventTriggerListener {
return;
}
- const clonedPayload = structuredClone(payload);
-
- await this.enrichDestroyedEvent(clonedPayload);
await this.handleEvent({
- payload: clonedPayload,
+ payload,
action: DatabaseEventAction.DESTROYED,
+ enrichPayload: (payloadToEnrich) =>
+ this.enrichDestroyedEvent(payloadToEnrich),
});
}
@@ -155,10 +153,8 @@ export class WorkflowDatabaseEventTriggerListener {
return;
}
- const clonedPayload = structuredClone(payload);
-
await this.handleEvent({
- payload: clonedPayload,
+ payload,
action: DatabaseEventAction.UPSERTED,
});
}
@@ -349,12 +345,14 @@ export class WorkflowDatabaseEventTriggerListener {
return false;
}
- private async handleEvent({
+ private async handleEvent<TEvent extends ObjectRecordEvent>({
payload,
action,
+ enrichPayload,
}: {
- payload: WorkspaceEventBatch<ObjectRecordEvent>;
+ payload: WorkspaceEventBatch<TEvent>;
action: DatabaseEventAction;
+ enrichPayload?: (payload: WorkspaceEventBatch<TEvent>) => Promise<void>;
}) {
const workspaceId = payload.workspaceId;
const databaseEventName = payload.name;
@@ -368,23 +366,53 @@ export class WorkflowDatabaseEventTriggerListener {
return;
}
+ const workspace = await this.coreEntityCacheService.get(
+ 'workspaceEntity',
+ workspaceId,
+ );
+
+ if (!isDefined(workspace)) {
+ return;
+ }
+
+ const { twentyStandardFlatApplication, workspaceCustomFlatApplication } =
+ await this.applicationService.findWorkspaceTwentyStandardAndCustomApplicationOrThrow(
+ { workspace },
+ );
+
+ const standardAndCustomApplicationIds = new Set([
+ twentyStandardFlatApplication.id,
+ workspaceCustomFlatApplication.id,
+ ]);
+
+ const enrichedPayload = eventListeners.some(({ applicationId }) =>
+ standardAndCustomApplicationIds.has(applicationId),
+ )
+ ? await this.buildEnrichedPayload({ payload, enrichPayload })
+ : payload;
+
const admittedEventsByApplicationId = new Map<
- string | undefined,
+ string,
ObjectRecordEvent[]
>();
for (const eventListener of eventListeners) {
- const { installedApplication } = eventListener;
+ const { applicationId } = eventListener;
- if (!admittedEventsByApplicationId.has(installedApplication?.id)) {
+ if (!admittedEventsByApplicationId.has(applicationId)) {
admittedEventsByApplicationId.set(
- installedApplication?.id,
- await this.resolveAdmittedEvents({ payload, installedApplication }),
+ applicationId,
+ await this.resolveAdmittedEvents({
+ payload,
+ enrichedPayload,
+ applicationId,
+ standardAndCustomApplicationIds,
+ }),
);
}
for (const eventPayload of admittedEventsByApplicationId.get(
- installedApplication?.id,
+ applicationId,
) ?? []) {
const shouldTriggerJob = this.shouldTriggerJob({
eventPayload,
@@ -413,83 +441,77 @@ export class WorkflowDatabaseEventTriggerListener {
workspaceId: string,
databaseEventName: string,
): Promise<DatabaseEventTriggerListener[]> {
- const {
- workflowAutomatedTriggerMaps,
- flatWorkflowMaps,
- flatApplicationMaps,
- } = await this.workspaceCacheService.getOrRecompute(workspaceId, [
- 'workflowAutomatedTriggerMaps',
- 'flatWorkflowMaps',
- 'flatApplicationMaps',
- ]);
+ const { workflowAutomatedTriggerMaps, flatApplicationMaps } =
+ await this.workspaceCacheService.getOrRecompute(workspaceId, [
+ 'workflowAutomatedTriggerMaps',
+ 'flatApplicationMaps',
+ ]);
return Object.values(
workflowAutomatedTriggerMaps.byWorkflowId,
).flatMap<DatabaseEventTriggerListener>((trigger) => {
if (
!isCachedDatabaseEventTrigger(trigger) ||
- trigger.settings.eventName !== databaseEventName
+ trigger.settings.eventName !== databaseEventName ||
+ isApplicationInstallPending(flatApplicationMaps, trigger.applicationId)
) {
return [];
}
- const workflow = findFlatEntityByIdInFlatEntityMaps({
- flatEntityId: trigger.workflowId,
- flatEntityMaps: flatWorkflowMaps,
- });
+ return [trigger];
+ });
+ }
- if (!isDefined(workflow)) {
- return [trigger];
- }
+ private async buildEnrichedPayload<TEvent extends ObjectRecordEvent>({
+ payload,
+ enrichPayload,
+ }: {
+ payload: WorkspaceEventBatch<TEvent>;
+ enrichPayload?: (payload: WorkspaceEventBatch<TEvent>) => Promise<void>;
+ }): Promise<WorkspaceEventBatch<TEvent>> {
+ if (!isDefined(enrichPayload)) {
+ return payload;
+ }
- if (
- isApplicationInstallPending(flatApplicationMaps, workflow.applicationId)
- ) {
- return [];
- }
+ const enrichedPayload = structuredClone(payload);
- const application = findActiveFlatApplicationById(
- flatApplicationMaps,
- workflow.applicationId,
- );
+ await enrichPayload(enrichedPayload);
- return [
- {
- ...trigger,
- installedApplication: application?.canBeUninstalled
- ? application
- : undefined,
- },
- ];
- });
+ return enrichedPayload;
}
private async resolveAdmittedEvents({
payload,
- installedApplication,
+ enrichedPayload,
+ applicationId,
+ standardAndCustomApplicationIds,
}: {
payload: WorkspaceEventBatch<ObjectRecordEvent>;
- installedApplication: FlatApplication | undefined;
+ enrichedPayload: WorkspaceEventBatch<ObjectRecordEvent>;
+ applicationId: string;
+ standardAndCustomApplicationIds: Set<string>;
}): Promise<ObjectRecordEvent[]> {
- if (!isDefined(installedApplication)) {
+ if (standardAndCustomApplicationIds.has(applicationId)) {
const admittedRecordIds = await resolveAutomationAdmittedRecordIds({
- payload,
+ payload: enrichedPayload,
workspaceCacheService: this.workspaceCacheService,
recordAccessPolicyService: this.recordAccessPolicyService,
});
- return payload.events.filter((event) =>
+ return enrichedPayload.events.filter((event) =>
admittedRecordIds.has(event.recordId),
);
}
const {
+ flatApplicationMaps,
rolesPermissions,
roleIdsWithAllRecordsAccess,
flatRowLevelPermissionPredicateMaps,
flatRowLevelPermissionPredicateGroupMaps,
flatFieldMetadataMaps,
} = await this.workspaceCacheService.getOrRecompute(payload.workspaceId, [
+ 'flatApplicationMaps',
'rolesPermissions',
'roleIdsWithAllRecordsAccess',
'flatRowLevelPermissionPredicateMaps',
@@ -498,8 +520,10 @@ export class WorkflowDatabaseEventTriggerListener {
]);
return resolveEventsReadableByRole({
- roleId: installedApplication.defaultRoleId,
- owningApplicationId: installedApplication.id,
+ roleId:
+ findActiveFlatApplicationById(flatApplicationMaps, applicationId)
+ ?.defaultRoleId ?? null,
+ owningApplicationId: applicationId,
workspaceEventBatch: payload,
eventRecordAccessGate:
this.recordAccessPolicyService.buildEventRecordAccessGate(payload),