The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Remove the legacy workflow trigger and version workspace services (#27857)
Thomas Trompette09ada053cc39
diff --git a/packages/twenty-server/src/modules/workflow/common/utils/assert-workflow-version-has-steps.ts b/packages/twenty-server/src/modules/workflow/common/utils/assert-workflow-version-has-steps.tsdeleted file mode 100644index 128eb53686c..00000000000--- a/packages/twenty-server/src/modules/workflow/common/utils/assert-workflow-version-has-steps.ts+++ /dev/null@@ -1,24 +0,0 @@-import { msg } from '@lingui/core/macro';--import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';-import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';-import {- WorkflowTriggerException,- WorkflowTriggerExceptionCode,-} from 'src/modules/workflow/workflow-trigger/exceptions/workflow-trigger.exception';--export function assertWorkflowVersionHasSteps(- workflowVersion: WorkflowVersionWorkspaceEntity,-): asserts workflowVersion is WorkflowVersionWorkspaceEntity & {- steps: WorkflowAction[];-} {- if (workflowVersion.steps === null || workflowVersion.steps.length < 1) {- throw new WorkflowTriggerException(- 'Workflow version does not contain at least one step',- WorkflowTriggerExceptionCode.INVALID_WORKFLOW_VERSION,- {- userFriendlyMessage: msg`Workflow version does not contain at least one step`,- },- );- }-}diff --git a/packages/twenty-server/src/modules/workflow/common/utils/assert-workflow-version-trigger-is-defined.util.ts b/packages/twenty-server/src/modules/workflow/common/utils/assert-workflow-version-trigger-is-defined.util.tsdeleted file mode 100644index 871436794f1..00000000000--- a/packages/twenty-server/src/modules/workflow/common/utils/assert-workflow-version-trigger-is-defined.util.ts+++ /dev/null@@ -1,27 +0,0 @@-import { msg } from '@lingui/core/macro';--import { type WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';-import {- WorkflowTriggerException,- WorkflowTriggerExceptionCode,-} from 'src/modules/workflow/workflow-trigger/exceptions/workflow-trigger.exception';-import { type WorkflowTrigger } from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';--export function assertWorkflowVersionTriggerIsDefined(- workflowVersion: WorkflowVersionWorkspaceEntity,-): asserts workflowVersion is Omit<- WorkflowVersionWorkspaceEntity,- 'trigger'-> & {- trigger: WorkflowTrigger;-} {- if (!workflowVersion.trigger) {- throw new WorkflowTriggerException(- 'Workflow version does not contain trigger',- WorkflowTriggerExceptionCode.INVALID_WORKFLOW_VERSION,- {- userFriendlyMessage: msg`Workflow version does not contain trigger`,- },- );- }-}diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-builder.module.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-builder.module.tsindex 291a491c807..a6c9daaa9d3 100644--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-builder.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-builder.module.ts@@ -2,19 +2,16 @@ import { Module } from '@nestjs/common';import { WorkflowSchemaModule } from 'src/modules/workflow/workflow-builder/workflow-schema/workflow-schema.module';import { WorkflowVersionStepModule } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module';-import { WorkflowVersionModule } from 'src/modules/workflow/workflow-builder/workflow-version/workflow-version.module';import { WorkflowVersionEdgeModule } from 'src/modules/workflow/workflow-builder/workflow-version-edge/workflow-version-edge.module';@Module({imports: [WorkflowSchemaModule,- WorkflowVersionModule,WorkflowVersionStepModule,WorkflowVersionEdgeModule,],exports: [WorkflowSchemaModule,- WorkflowVersionModule,WorkflowVersionStepModule,WorkflowVersionEdgeModule,],diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.module.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.module.tsdeleted file mode 100644index 84cffafff1c..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.module.ts+++ /dev/null@@ -1,23 +0,0 @@-import { Module } from '@nestjs/common';--import { CacheLockModule } from 'src/engine/core-modules/cache-lock/cache-lock.module';-import { RecordPositionModule } from 'src/engine/core-modules/record-position/record-position.module';-import { WorkflowCoreModule } from 'src/engine/core-modules/workflow/workflow-core.module';-import { WorkflowVersionCoreModule } from 'src/engine/core-modules/workflow/workflow-version-core.module';-import { WorkflowCommonModule } from 'src/modules/workflow/common/workflow-common.module';-import { WorkflowVersionStepModule } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.module';-import { WorkflowVersionWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service';--@Module({- imports: [- WorkflowVersionStepModule,- WorkflowCommonModule,- RecordPositionModule,- CacheLockModule,- WorkflowCoreModule,- WorkflowVersionCoreModule,- ],- providers: [WorkflowVersionWorkspaceService],- exports: [WorkflowVersionWorkspaceService],-})-export class WorkflowVersionModule {}diff --git a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service.tsdeleted file mode 100644index 768b2c32a65..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-builder/workflow-version/workflow-version.workspace-service.ts+++ /dev/null@@ -1,429 +0,0 @@-import { Injectable } from '@nestjs/common';--import { isDefined } from 'twenty-shared/utils';-import { TRIGGER_STEP_ID } from 'twenty-shared/workflow';--import { WithLock } from 'src/engine/core-modules/cache-lock/with-lock.decorator';-import { RecordPositionService } from 'src/engine/core-modules/record-position/services/record-position.service';-import { type WorkflowStepPositionUpdateInput } from 'src/engine/core-modules/workflow/dtos/update-workflow-step-position-update.input';-import { WorkflowStatus } from 'src/engine/core-modules/workflow/enums/workflow-status.enum';-import { WorkflowCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-core-sync.service';-import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';-import {- WorkflowVersionStepException,- WorkflowVersionStepExceptionCode,-} from 'src/modules/workflow/common/exceptions/workflow-version-step.exception';-import {- WorkflowVersionStatus,- type WorkflowVersionWorkspaceEntity,-} from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';-import { WorkflowWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';-import { assertWorkflowVersionHasSteps } from 'src/modules/workflow/common/utils/assert-workflow-version-has-steps';-import { assertWorkflowVersionIsDraft } from 'src/modules/workflow/common/utils/assert-workflow-version-is-draft.util';-import { assertWorkflowVersionTriggerIsDefined } from 'src/modules/workflow/common/utils/assert-workflow-version-trigger-is-defined.util';-import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';-import { computeWorkflowStepPositions } from 'src/modules/workflow/workflow-builder/utils/compute-workflow-step-positions.util';-import { remapDuplicatedStepDestinations } from 'src/modules/workflow/workflow-builder/utils/remap-duplicated-step-destinations.util';-import { WorkflowVersionStepOperationsWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step-operations.workspace-service';-import { WorkflowVersionStepWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-version-step/workflow-version-step.workspace-service';-import { type WorkflowAction } from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';--@Injectable()-export class WorkflowVersionWorkspaceService {- constructor(- private readonly workspaceOrmManager: WorkspaceOrmManager,- private readonly workflowVersionStepWorkspaceService: WorkflowVersionStepWorkspaceService,- private readonly workflowVersionStepOperationsWorkspaceService: WorkflowVersionStepOperationsWorkspaceService,- private readonly recordPositionService: RecordPositionService,- private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,- private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,- private readonly workflowCoreSyncService: WorkflowCoreSyncService,- ) {}-- @WithLock('workflowId')- async createDraftFromWorkflowVersion({- workspaceId,- workflowId,- workflowVersionIdToCopy,- }: {- workspaceId: string;- workflowId: string;- workflowVersionIdToCopy: string;- }) {- const authContext = buildSystemAuthContext(workspaceId);-- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowVersionRepository =- this.workspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- const workflowVersionToCopy = await workflowVersionRepository.findOne({- where: {- id: workflowVersionIdToCopy,- workflowId,- },- });-- if (!isDefined(workflowVersionToCopy)) {- throw new WorkflowVersionStepException(- 'WorkflowVersion to copy not found',- WorkflowVersionStepExceptionCode.NOT_FOUND,- );- }-- assertWorkflowVersionTriggerIsDefined(workflowVersionToCopy);- assertWorkflowVersionHasSteps(workflowVersionToCopy);-- const newWorkflowVersionTrigger = workflowVersionToCopy.trigger;- const newWorkflowVersionSteps: WorkflowAction[] = [];-- for (const step of workflowVersionToCopy.steps) {- const duplicatedStep =- await this.workflowVersionStepWorkspaceService.createDraftStep({- step,- workspaceId,- });-- newWorkflowVersionSteps.push(duplicatedStep);- }-- const existingDraftVersion = await workflowVersionRepository.findOne({- where: {- workflowId,- status: WorkflowVersionStatus.DRAFT,- },- });-- if (isDefined(existingDraftVersion)) {- assertWorkflowVersionIsDraft(existingDraftVersion);-- await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(- workspaceId,- async (scopedRepository) => {- await scopedRepository.update(existingDraftVersion.id, {- steps: newWorkflowVersionSteps,- trigger: newWorkflowVersionTrigger,- });-- return existingDraftVersion.id;- },- );-- return {- ...existingDraftVersion,- name: existingDraftVersion.name ?? '',- steps: newWorkflowVersionSteps,- trigger: newWorkflowVersionTrigger,- };- }-- const workflowVersionsCount = await workflowVersionRepository.count({- where: {- workflowId,- },- });-- const position = await this.recordPositionService.buildRecordPosition({- value: 'first',- objectMetadata: {- isCustom: false,- nameSingular: 'workflowVersion',- },- workspaceId,- });-- let draftWorkflowVersion: WorkflowVersionWorkspaceEntity | undefined;-- await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(- workspaceId,- async (scopedRepository) => {- const insertResult = await scopedRepository.insert({- workflowId,- name: `v${workflowVersionsCount + 1}`,- status: WorkflowVersionStatus.DRAFT,- steps: newWorkflowVersionSteps,- trigger: newWorkflowVersionTrigger,- position,- });-- draftWorkflowVersion = insertResult- .generatedMaps[0] as WorkflowVersionWorkspaceEntity;-- return draftWorkflowVersion.id;- },- );-- if (!isDefined(draftWorkflowVersion)) {- throw new WorkflowVersionStepException(- 'Failed to create draft workflow version',- WorkflowVersionStepExceptionCode.NOT_FOUND,- );- }-- return {- ...draftWorkflowVersion,- name: draftWorkflowVersion.name ?? '',- steps: newWorkflowVersionSteps,- trigger: newWorkflowVersionTrigger,- };- }, authContext);- }-- async duplicateWorkflow({- workspaceId,- workflowIdToDuplicate,- workflowVersionIdToCopy,- }: {- workspaceId: string;- workflowIdToDuplicate: string;- workflowVersionIdToCopy: string;- }) {- const authContext = buildSystemAuthContext(workspaceId);-- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowRepository = this.workspaceOrmManager.getRepository(- 'workflow',- {- shouldBypassPermissionChecks: true,- },- );-- const workflowVersionRepository =- this.workspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- const sourceWorkflow = await workflowRepository.findOne({- where: {- id: workflowIdToDuplicate,- },- });-- if (!isDefined(sourceWorkflow)) {- throw new WorkflowVersionStepException(- 'Source workflow not found',- WorkflowVersionStepExceptionCode.NOT_FOUND,- );- }-- const sourceVersion = await workflowVersionRepository.findOne({- where: {- id: workflowVersionIdToCopy,- workflowId: workflowIdToDuplicate,- },- });-- if (!isDefined(sourceVersion)) {- throw new WorkflowVersionStepException(- 'WorkflowVersion to copy not found',- WorkflowVersionStepExceptionCode.NOT_FOUND,- );- }-- assertWorkflowVersionTriggerIsDefined(sourceVersion);- assertWorkflowVersionHasSteps(sourceVersion);-- const workflowPosition =- await this.recordPositionService.buildRecordPosition({- value: 'first',- objectMetadata: {- isCustom: false,- nameSingular: 'workflow',- },- workspaceId,- });-- const insertWorkflowResult = await workflowRepository.insert({- name: `${sourceWorkflow.name} (Duplicate)`,- statuses: [WorkflowStatus.DRAFT],- position: workflowPosition,- });-- const newWorkflowId = (- insertWorkflowResult.generatedMaps[0] as WorkflowWorkspaceEntity- ).id;-- await this.workflowCoreSyncService.upsertToCore(workspaceId, [- newWorkflowId,- ]);-- const versionPosition =- await this.recordPositionService.buildRecordPosition({- value: 'first',- objectMetadata: {- isCustom: false,- nameSingular: 'workflowVersion',- },- workspaceId,- });-- const newTrigger = sourceVersion.trigger;- const sourceToClonedPairs: {- source: WorkflowAction;- duplicated: WorkflowAction;- }[] = [];- const clonedStepIdBySourceStepId = new Map<string, string>();-- for (const step of sourceVersion.steps ?? []) {- const clonedStep =- await this.workflowVersionStepOperationsWorkspaceService.cloneStep({- step,- workspaceId,- });-- sourceToClonedPairs.push({- source: step,- duplicated: clonedStep,- });- clonedStepIdBySourceStepId.set(step.id, clonedStep.id);- }-- const { trigger: remappedTrigger, steps: remappedSteps } = isDefined(- newTrigger,- )- ? remapDuplicatedStepDestinations({- trigger: newTrigger,- sourceToClonedPairs,- clonedStepIdBySourceStepId,- })- : {- trigger: undefined,- steps: sourceToClonedPairs.map(({ duplicated }) => duplicated),- };-- let newDraftVersion: WorkflowVersionWorkspaceEntity | undefined;-- await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(- workspaceId,- async (scopedRepository) => {- const insertVersionResult = await scopedRepository.insert({- workflowId: newWorkflowId,- name: 'v1',- status: WorkflowVersionStatus.DRAFT,- position: versionPosition,- steps: remappedSteps,- trigger: remappedTrigger,- });-- newDraftVersion = insertVersionResult- .generatedMaps[0] as WorkflowVersionWorkspaceEntity;-- return newDraftVersion.id;- },- );-- if (!isDefined(newDraftVersion)) {- throw new WorkflowVersionStepException(- 'Failed to duplicate workflow version',- WorkflowVersionStepExceptionCode.NOT_FOUND,- );- }-- return {- ...newDraftVersion,- name: newDraftVersion.name ?? '',- steps: remappedSteps,- trigger: remappedTrigger ?? null,- };- }, authContext);- }-- async updateWorkflowVersionPositions({- workflowVersionId,- positions,- workspaceId,- }: {- workflowVersionId: string;- positions: WorkflowStepPositionUpdateInput[];- workspaceId: string;- }) {- const authContext = buildSystemAuthContext(workspaceId);-- await this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowVersionRepository =- this.workspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- const workflowVersion = await workflowVersionRepository.findOneOrFail({- where: {- id: workflowVersionId,- },- });-- assertWorkflowVersionIsDraft(workflowVersion);-- const triggerPosition = positions.find(- (position) => position.id === TRIGGER_STEP_ID,- );-- const updatedTrigger =- isDefined(triggerPosition) && isDefined(workflowVersion.trigger)- ? {- ...workflowVersion.trigger,- position: triggerPosition.position,- }- : undefined;-- const updatedSteps = workflowVersion.steps?.map((step) => {- const updatedStep = positions.find(- (position) => position.id === step.id,- );-- if (updatedStep) {- return {- ...step,- position: updatedStep.position,- };- }-- return step;- });-- const updatePayload = {- ...(!isDefined(updatedTrigger) ? {} : { trigger: updatedTrigger }),- ...(!isDefined(updatedSteps) ? {} : { steps: updatedSteps }),- };-- await this.workflowVersionCoreSyncService.writeWorkflowVersionAndMirror(- workspaceId,- async (scopedRepository) => {- await scopedRepository.update(workflowVersionId, updatePayload);-- return workflowVersionId;- },- );- }, authContext);- }-- async autoLayoutWorkflowVersion({- workflowVersionId,- workspaceId,- }: {- workflowVersionId: string;- workspaceId: string;- }) {- const workflowVersion =- await this.workflowCommonWorkspaceService.getWorkflowVersionOrFail({- workspaceId,- workflowVersionId,- });-- assertWorkflowVersionIsDraft(workflowVersion);-- await this.updateWorkflowVersionPositions({- workflowVersionId,- positions: computeWorkflowStepPositions({- trigger: workflowVersion.trigger,- steps: workflowVersion.steps ?? [],- }),- workspaceId,- });- }-}diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/workflow-trigger.module.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/workflow-trigger.module.tsindex 91b49783196..65a783d0c91 100644--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/workflow-trigger.module.ts+++ b/packages/twenty-server/src/modules/workflow/workflow-trigger/workflow-trigger.module.ts@@ -12,7 +12,6 @@ import { WorkflowCoreConsistencyModule } from 'src/modules/workflow/workflow-corimport { WorkflowRunnerModule } from 'src/modules/workflow/workflow-runner/workflow-runner.module';import { AutomatedTriggerModule } from 'src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.module';import { WorkflowTriggerJob } from 'src/modules/workflow/workflow-trigger/jobs/workflow-trigger.job';-import { WorkflowTriggerWorkspaceService } from 'src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service';@Module({imports: [@@ -26,7 +25,6 @@ import { WorkflowTriggerWorkspaceService } from 'src/modules/workflow/workflow-tWorkflowVersionCoreModule,WorkflowVersionValidationModule,],- providers: [WorkflowTriggerWorkspaceService, WorkflowTriggerJob],- exports: [WorkflowTriggerWorkspaceService],+ providers: [WorkflowTriggerJob],})export class WorkflowTriggerModule {}diff --git a/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts b/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.tsdeleted file mode 100644index ef955e3d517..00000000000--- a/packages/twenty-server/src/modules/workflow/workflow-trigger/workspace-services/workflow-trigger.workspace-service.ts+++ /dev/null@@ -1,771 +0,0 @@-import { msg } from '@lingui/core/macro';-import { Injectable, Logger } from '@nestjs/common';-import {- type ActorMetadata,- CommandMenuItemAvailabilityType,-} from 'twenty-shared/types';-import { isDefined } from 'twenty-shared/utils';-import { WorkflowActionType } from 'twenty-shared/workflow';--import { InjectCacheStorage } from 'src/engine/core-modules/cache-storage/decorators/cache-storage.decorator';-import { CacheStorageService } from 'src/engine/core-modules/cache-storage/services/cache-storage.service';-import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';-import { AutomatedTriggerType } from 'src/engine/core-modules/workflow/enums/automated-trigger-type.enum';-import { buildCoreDispatchIds } from 'src/engine/core-modules/workflow/utils/build-core-dispatch-ids.util';-import { WorkflowVersionCoreSyncService } from 'src/engine/core-modules/workflow/services/workflow-version-core-sync.service';-import { CommandMenuItemService } from 'src/engine/metadata-modules/command-menu-item/command-menu-item.service';-import { EngineComponentKey } from 'src/engine/metadata-modules/command-menu-item/enums/engine-component-key.enum';-import { type WorkspaceTransactionScope } from 'src/engine/twenty-orm/types/workspace-transaction-scope.type';-import { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';-import { type WorkspaceRepository } from 'src/engine/twenty-orm/repository/workspace-repository';-import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-system-auth-context.util';-import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';-import { WorkspaceEventEmitter } from 'src/engine/workspace-event-emitter/workspace-event-emitter';-import {- WorkflowVersionStatus,- type WorkflowVersionWorkspaceEntity,-} from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';-import { type WorkflowWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow.workspace-entity';-import { assertWorkflowVersionTriggerIsDefined } from 'src/modules/workflow/common/utils/assert-workflow-version-trigger-is-defined.util';-import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';-import { getPickRecordLoadBalanceConfigError } from 'src/modules/workflow/workflow-builder/workflow-validation/utils/get-pick-record-load-balance-config-error.util';-import { WorkflowVersionValidationWorkspaceService } from 'src/modules/workflow/workflow-builder/workflow-validation/workflow-version-validation.workspace-service';-import { CodeStepBuildService } from 'src/modules/workflow/workflow-builder/workflow-version-step/code-step/services/code-step-build.service';-import {- type WorkflowAction,- type WorkflowPickRecordAction,-} from 'src/modules/workflow/workflow-executor/workflow-actions/types/workflow-action.type';-import { WorkflowRunnerWorkspaceService } from 'src/modules/workflow/workflow-runner/workspace-services/workflow-runner.workspace-service';-import { WORKFLOW_VERSION_STATUS_UPDATED } from 'src/modules/workflow/workflow-status/constants/workflow-version-status-updated.constants';-import { type WorkflowVersionStatusUpdate } from 'src/modules/workflow/workflow-status/jobs/workflow-statuses-update.job';-import { AutomatedTriggerWorkspaceService } from 'src/modules/workflow/workflow-trigger/automated-trigger/automated-trigger.workspace-service';-import { type DatabaseEventTriggerSettings } from 'src/modules/workflow/workflow-trigger/automated-trigger/constants/automated-trigger-settings';-import { WORKFLOW_CRON_TRIGGER_CACHE_KEY } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/constants/workflow-cron-trigger-cache-key.constant';-import { publishCronTriggerCacheEntry } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/utils/publish-cron-trigger-cache-entry.util';-import { type CachedCronTrigger } from 'src/modules/workflow/workflow-trigger/automated-trigger/crons/types/cached-cron-trigger.type';-import {- WorkflowTriggerException,- WorkflowTriggerExceptionCode,-} from 'src/modules/workflow/workflow-trigger/exceptions/workflow-trigger.exception';-import {- type WorkflowManualTrigger,- WorkflowTriggerType,-} from 'src/modules/workflow/workflow-trigger/types/workflow-trigger.type';-import { assertVersionCanBeActivated } from 'src/modules/workflow/workflow-trigger/utils/assert-version-can-be-activated.util';-import { computeCronPatternFromSchedule } from 'src/modules/workflow/workflow-trigger/utils/compute-cron-pattern-from-schedule';-import { getWorkflowCommandMenuItemLabel } from 'src/modules/workflow/workflow-trigger/utils/get-workflow-command-menu-item-label.util';-import { assertNever } from 'src/utils/assert';--@Injectable()-export class WorkflowTriggerWorkspaceService {- private readonly logger = new Logger(WorkflowTriggerWorkspaceService.name);-- constructor(- private readonly workflowVersionValidationWorkspaceService: WorkflowVersionValidationWorkspaceService,- private readonly workspaceOrmManager: WorkspaceOrmManager,- private readonly workflowCommonWorkspaceService: WorkflowCommonWorkspaceService,- private readonly codeStepBuildService: CodeStepBuildService,- private readonly workflowRunnerWorkspaceService: WorkflowRunnerWorkspaceService,- private readonly automatedTriggerWorkspaceService: AutomatedTriggerWorkspaceService,- private readonly workspaceEventEmitter: WorkspaceEventEmitter,- private readonly commandMenuItemService: CommandMenuItemService,- private readonly workflowVersionCoreSyncService: WorkflowVersionCoreSyncService,- @InjectCacheStorage(CacheStorageNamespace.ModuleWorkflow)- private readonly cacheStorageService: CacheStorageService,- ) {}-- async runWorkflowVersion({- workflowVersionId,- payload,- createdBy,- workflowRunId,- workspaceId,- }: {- workflowVersionId: string;- payload: object;- createdBy: ActorMetadata;- workflowRunId?: string;- workspaceId: string;- }) {- return this.workflowRunnerWorkspaceService.run({- workspaceId,- workflowRunId,- workflowVersionId,- payload,- source: createdBy,- });- }-- async activateWorkflowVersion(- workflowVersionId: string,- workspaceId: string,- ) {- const authContext = buildSystemAuthContext(workspaceId);-- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowVersionRepository =- this.workspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- const workflowVersionNullable = await workflowVersionRepository.findOne({- where: { id: workflowVersionId },- });-- const workflowVersion =- await this.workflowCommonWorkspaceService.getValidWorkflowVersionOrFail(- workflowVersionNullable,- );-- const workflowRepository =- this.workspaceOrmManager.getRepository<WorkflowWorkspaceEntity>(- 'workflow',- { shouldBypassPermissionChecks: true },- );-- const workflow = await workflowRepository.findOne({- where: { id: workflowVersion.workflowId },- });-- if (!workflow) {- throw new WorkflowTriggerException(- 'No workflow found',- WorkflowTriggerExceptionCode.INVALID_WORKFLOW_VERSION,- );- }-- await this.workflowVersionValidationWorkspaceService.assertWorkflowVersionIsActivableOrThrow(- {- workspaceId,- trigger: workflowVersion.trigger,- steps: workflowVersion.steps,- },- );-- assertVersionCanBeActivated(workflowVersion, workflow);-- await this.assertPickRecordLoadBalanceConfigIsValid({- steps: workflowVersion.steps ?? [],- workspaceId,- });-- await this.codeStepBuildService.buildCodeStepsFromSourceForSteps({- workspaceId,- steps: workflowVersion.steps ?? [],- });-- await this.codeStepBuildService.switchCodeStepLogicFunctionsToPrebuilt({- workspaceId,- steps: workflowVersion.steps ?? [],- });-- await this.performActivationSteps(workflow, workflowVersion, workspaceId);-- return true;- }, authContext);- }-- private async assertPickRecordLoadBalanceConfigIsValid({- steps,- workspaceId,- }: {- steps: WorkflowAction[];- workspaceId: string;- }) {- const pickRecordSteps = steps.filter(- (step): step is WorkflowPickRecordAction =>- step.type === WorkflowActionType.PICK_RECORD,- );-- if (pickRecordSteps.length === 0) {- return;- }-- const { objectIdByNameSingular, flatFieldMetadataMaps } =- await this.workflowCommonWorkspaceService.getFlatEntityMaps(workspaceId);-- for (const step of pickRecordSteps) {- const loadBalanceError = getPickRecordLoadBalanceConfigError({- step,- objectIdByNameSingular,- flatFieldMetadataMaps,- });-- if (isDefined(loadBalanceError)) {- throw new WorkflowTriggerException(- loadBalanceError,- WorkflowTriggerExceptionCode.INVALID_WORKFLOW_VERSION,- );- }- }- }-- async deactivateWorkflowVersion(- workflowVersionId: string,- workspaceId: string,- ) {- const authContext = buildSystemAuthContext(workspaceId);-- return this.workspaceOrmManager.executeInWorkspaceContext(async () => {- const workflowVersionRepository =- this.workspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- await this.performDeactivationSteps(- workflowVersionId,- workflowVersionRepository,- workspaceId,- );-- return true;- }, authContext);- }-- async stopWorkflowRun(workflowRunId: string, workspaceId: string) {- return this.workflowRunnerWorkspaceService.stopWorkflowRun(- workspaceId,- workflowRunId,- );- }-- async retryWorkflowRun(workflowRunId: string, workspaceId: string) {- return this.workflowRunnerWorkspaceService.retryWorkflowRun(- workspaceId,- workflowRunId,- );- }-- private async mirrorVersionStatusChangeInTransaction(- workflowVersionId: string,- workspaceId: string,- transactionScope: WorkspaceTransactionScope,- ): Promise<string | null> {- const workflowVersion = await transactionScope- .getRepository<WorkflowVersionWorkspaceEntity>('workflowVersion', {- shouldBypassPermissionChecks: true,- })- .findOne({ where: { id: workflowVersionId } });-- if (!isDefined(workflowVersion)) {- return null;- }-- const mirrorResult =- await this.workflowVersionCoreSyncService.mirrorWorkflowVersionWrite({- workspaceId,- transactionScope,- workflowVersion,- });-- return (- mirrorResult?.coreWorkflowVersionId ??- workflowVersion.coreWorkflowVersionId ??- null- );- }-- private async performActivationSteps(- workflow: WorkflowWorkspaceEntity,- workflowVersion: WorkflowVersionWorkspaceEntity,- workspaceId: string,- ) {- let previousVersion: WorkflowVersionWorkspaceEntity | null = null;-- let mirroredCoreWorkflowVersionIdForCommandMenuItem: string | null = null;-- await this.workspaceOrmManager.runInWorkspaceTransaction(- async (transactionScope) => {- await transactionScope.executeRawQuery(- `SELECT id FROM "${getWorkspaceSchemaName(workspaceId)}".workflow WHERE id = $1 FOR NO KEY UPDATE`,- [workflow.id],- );- await transactionScope.executeRawQuery(- `SELECT id FROM "${getWorkspaceSchemaName(workspaceId)}"."workflowVersion" WHERE "workflowId" = $1 ORDER BY id FOR NO KEY UPDATE`,- [workflow.id],- );-- const unchangedVersion = await transactionScope.executeRawQuery(- `SELECT id FROM "${getWorkspaceSchemaName(workspaceId)}"."workflowVersion" WHERE id = $1- AND status = $2 AND trigger IS NOT DISTINCT FROM $3::jsonb AND steps IS NOT DISTINCT FROM $4::jsonb`,- [- workflowVersion.id,- workflowVersion.status,- JSON.stringify(workflowVersion.trigger),- JSON.stringify(workflowVersion.steps),- ],- );-- if (unchangedVersion.length !== 1) {- throw new WorkflowTriggerException(- 'Workflow version changed during activation',- WorkflowTriggerExceptionCode.INVALID_INPUT,- {- userFriendlyMessage: msg`Workflow version changed, please reload and retry`,- },- );- }-- const transactionalWorkflowRepository =- transactionScope.getRepository<WorkflowWorkspaceEntity>('workflow', {- shouldBypassPermissionChecks: true,- });- const transactionalWorkflowVersionRepository =- transactionScope.getRepository<WorkflowVersionWorkspaceEntity>(- 'workflowVersion',- { shouldBypassPermissionChecks: true },- );-- const currentWorkflow =- await transactionalWorkflowRepository.findOneOrFail({- where: { id: workflow.id },- });-- if (currentWorkflow.lastPublishedVersionId !== workflowVersion.id) {- if (currentWorkflow.lastPublishedVersionId) {- previousVersion =- await transactionalWorkflowVersionRepository.findOne({- where: { id: currentWorkflow.lastPublishedVersionId },- });-- if (previousVersion?.status === WorkflowVersionStatus.ACTIVE) {- await this.disableAutomatedTrigger(previousVersion, workspaceId, {- transactionScope,- });- }-- await transactionalWorkflowVersionRepository.update(- { id: currentWorkflow.lastPublishedVersionId },- { status: WorkflowVersionStatus.ARCHIVED },- );-- await this.mirrorVersionStatusChangeInTransaction(- currentWorkflow.lastPublishedVersionId,- workspaceId,- transactionScope,- );- }-- await transactionalWorkflowRepository.update(- { id: workflow.id },- { lastPublishedVersionId: workflowVersion.id },- );- }-- const activeWorkflowVersions =- await transactionalWorkflowVersionRepository.find({- where: {- workflowId: workflowVersion.workflowId,- status: WorkflowVersionStatus.ACTIVE,- },- });-- if (activeWorkflowVersions.length > 0) {- throw new WorkflowTriggerException(- 'Cannot have more than one active workflow version',- WorkflowTriggerExceptionCode.FORBIDDEN,- {- userFriendlyMessage: msg`Cannot have more than one active workflow version`,- },- );- }-- await transactionalWorkflowVersionRepository.update(- { id: workflowVersion.id },- { status: WorkflowVersionStatus.ACTIVE },- );-- const mirroredCoreWorkflowVersionId =- await this.mirrorVersionStatusChangeInTransaction(- workflowVersion.id,- workspaceId,- transactionScope,- );-- if (!isDefined(mirroredCoreWorkflowVersionId)) {- throw new WorkflowTriggerException(- 'Activated workflow version has no core mapping',- WorkflowTriggerExceptionCode.INVALID_WORKFLOW_VERSION,- );- }-- await transactionScope.executeRawQuery(- `UPDATE core."workflow" SET "lastPublishedVersionId" = $3, "lastPublishedCoreWorkflowVersionId" = $4, "updatedAt" = now() WHERE "workspaceId" = $1 AND "workspaceWorkflowId" = $2`,- [- workspaceId,- workflow.id,- workflowVersion.id,- mirroredCoreWorkflowVersionId,- ],- );-- mirroredCoreWorkflowVersionIdForCommandMenuItem =- mirroredCoreWorkflowVersionId;-- await this.enableAutomatedTrigger(workflowVersion, workspaceId, {- transactionScope,- coreWorkflowVersionId: mirroredCoreWorkflowVersionId,- });- },- );-- if (isDefined(previousVersion)) {- await this.deleteCommandMenuItem(previousVersion, workspaceId);- await this.emitStatusUpdateEvents(- previousVersion,- WorkflowVersionStatus.ARCHIVED,- workspaceId,- );- }-- await this.createOrUpdateCommandMenuItem(- workflow,- workflowVersion,- workspaceId,- mirroredCoreWorkflowVersionIdForCommandMenuItem,- );-- await this.workflowVersionCoreSyncService.invalidateAutomatedTriggerMaps(- workspaceId,- );-- await this.emitStatusUpdateEvents(- workflowVersion,- WorkflowVersionStatus.ACTIVE,- workspaceId,- );- }-- private async performDeactivationSteps(- workflowVersionId: string,- workflowVersionRepository: WorkspaceRepository<WorkflowVersionWorkspaceEntity>,- workspaceId: string,- ) {- const workflowVersionNullable = await workflowVersionRepository.findOne({- where: { id: workflowVersionId },- });-- const workflowVersion =- await this.workflowCommonWorkspaceService.getValidWorkflowVersionOrFail(- workflowVersionNullable,- );-- if (workflowVersion.status !== WorkflowVersionStatus.ACTIVE) {- return;- }-- await this.workspaceOrmManager.runInWorkspaceTransaction(- async (transactionScope) => {- await transactionScope- .getRepository<WorkflowVersionWorkspaceEntity>('workflowVersion', {- shouldBypassPermissionChecks: true,- })- .update(- { id: workflowVersion.id },- { status: WorkflowVersionStatus.DEACTIVATED },- );-- await this.mirrorVersionStatusChangeInTransaction(- workflowVersion.id,- workspaceId,- transactionScope,- );-- await this.disableAutomatedTrigger(workflowVersion, workspaceId, {- transactionScope,- });- },- );-- await this.deleteCommandMenuItem(workflowVersion, workspaceId);-- await this.workflowVersionCoreSyncService.invalidateAutomatedTriggerMaps(- workspaceId,- );-- await this.emitStatusUpdateEvents(- workflowVersion,- WorkflowVersionStatus.DEACTIVATED,- workspaceId,- );- }-- private async resolveManualTriggerAvailability(- trigger: WorkflowManualTrigger,- workspaceId: string,- ): Promise<{- availabilityType: CommandMenuItemAvailabilityType;- availabilityObjectMetadataId: string | undefined;- }> {- const availability = trigger.settings.availability;-- let availabilityType = CommandMenuItemAvailabilityType.GLOBAL;- let availabilityObjectMetadataId: string | undefined;-- if (availability) {- switch (availability.type) {- case 'GLOBAL':- availabilityType = CommandMenuItemAvailabilityType.GLOBAL;- break;- case 'SINGLE_RECORD':- case 'BULK_RECORDS': {- availabilityType = CommandMenuItemAvailabilityType.RECORD_SELECTION;-- const { objectIdByNameSingular } =- await this.workflowCommonWorkspaceService.getFlatEntityMaps(- workspaceId,- );-- const objectId =- objectIdByNameSingular[availability.objectNameSingular];-- if (!objectId) {- throw new WorkflowTriggerException(- `Object metadata not found for object: ${availability.objectNameSingular}`,- WorkflowTriggerExceptionCode.INVALID_WORKFLOW_VERSION,- );- }-- availabilityObjectMetadataId = objectId;- break;- }- }- }-- return { availabilityType, availabilityObjectMetadataId };- }-- private async createOrUpdateCommandMenuItem(- workflow: WorkflowWorkspaceEntity,- workflowVersion: WorkflowVersionWorkspaceEntity,- workspaceId: string,- mirroredCoreWorkflowVersionId: string | null,- ) {- assertWorkflowVersionTriggerIsDefined(workflowVersion);-- if (workflowVersion.trigger.type !== WorkflowTriggerType.MANUAL) {- return;- }-- const trigger = workflowVersion.trigger as WorkflowManualTrigger;-- const { availabilityType, availabilityObjectMetadataId } =- await this.resolveManualTriggerAvailability(trigger, workspaceId);-- const label = getWorkflowCommandMenuItemLabel(workflow);-- const coreWorkflowVersionId =- mirroredCoreWorkflowVersionId ?? workflowVersion.coreWorkflowVersionId;-- const existingCommandMenuItem =- (isDefined(coreWorkflowVersionId)- ? await this.commandMenuItemService.findByCoreWorkflowVersionId(- coreWorkflowVersionId,- workspaceId,- )- : null) ??- (await this.commandMenuItemService.findByWorkflowVersionId(- workflowVersion.id,- workspaceId,- ));-- if (existingCommandMenuItem) {- await this.commandMenuItemService.update(- {- id: existingCommandMenuItem.id,- label,- shortLabel: label,- icon: trigger.settings.icon,- isPinned: trigger.settings.isPinned,- availabilityType,- availabilityObjectMetadataId,- },- workspaceId,- );- } else {- await this.commandMenuItemService.create(- {- workflowVersionId: workflowVersion.id,- coreWorkflowVersionId: coreWorkflowVersionId ?? undefined,- engineComponentKey: EngineComponentKey.TRIGGER_WORKFLOW_VERSION,- label,- shortLabel: label,- icon: trigger.settings.icon,- isPinned: trigger.settings.isPinned,- availabilityType,- availabilityObjectMetadataId,- },- workspaceId,- );- }- }-- private async deleteCommandMenuItem(- workflowVersion: WorkflowVersionWorkspaceEntity,- workspaceId: string,- ) {- assertWorkflowVersionTriggerIsDefined(workflowVersion);-- if (workflowVersion.trigger.type !== WorkflowTriggerType.MANUAL) {- return;- }-- const existingCommandMenuItem =- (isDefined(workflowVersion.coreWorkflowVersionId)- ? await this.commandMenuItemService.findByCoreWorkflowVersionId(- workflowVersion.coreWorkflowVersionId,- workspaceId,- )- : null) ??- (await this.commandMenuItemService.findByWorkflowVersionId(- workflowVersion.id,- workspaceId,- ));-- if (existingCommandMenuItem) {- await this.commandMenuItemService.delete(- existingCommandMenuItem.id,- workspaceId,- );- }- }-- private async enableAutomatedTrigger(- workflowVersion: WorkflowVersionWorkspaceEntity,- workspaceId: string,- transactionContext?: {- transactionScope: WorkspaceTransactionScope;- coreWorkflowVersionId?: string | null;- },- ) {- assertWorkflowVersionTriggerIsDefined(workflowVersion);-- switch (workflowVersion.trigger.type) {- case WorkflowTriggerType.MANUAL:- case WorkflowTriggerType.WEBHOOK:- return;- case WorkflowTriggerType.DATABASE_EVENT: {- const settings = workflowVersion.trigger- .settings as DatabaseEventTriggerSettings;-- await this.automatedTriggerWorkspaceService.addAutomatedTrigger({- workflowId: workflowVersion.workflowId,- type: AutomatedTriggerType.DATABASE_EVENT,- settings,- workspaceId,- transactionScope: transactionContext?.transactionScope,- });-- return;- }- case WorkflowTriggerType.CRON: {- const pattern = computeCronPatternFromSchedule(workflowVersion.trigger);-- await this.automatedTriggerWorkspaceService.addAutomatedTrigger({- workflowId: workflowVersion.workflowId,- type: AutomatedTriggerType.CRON,- settings: { pattern },- workspaceId,- transactionScope: transactionContext?.transactionScope,- });-- const cachedTrigger: CachedCronTrigger = {- workspaceId,- workflowId: workflowVersion.workflowId,- pattern,- ...buildCoreDispatchIds({- coreWorkflowVersionId:- transactionContext?.coreWorkflowVersionId ??- workflowVersion.coreWorkflowVersionId,- workspaceWorkflowVersionId: workflowVersion.id,- }),- };-- const publishCronCache = () =>- publishCronTriggerCacheEntry({- cacheStorageService: this.cacheStorageService,- cachedTrigger,- logger: this.logger,- });-- if (isDefined(transactionContext)) {- transactionContext.transactionScope.afterCommit(publishCronCache);- } else {- await publishCronCache();- }-- return;- }- default:- assertNever(workflowVersion.trigger);- }- }-- private async disableAutomatedTrigger(- workflowVersion: WorkflowVersionWorkspaceEntity,- workspaceId: string,- transactionContext?: {- transactionScope: WorkspaceTransactionScope;- },- ) {- assertWorkflowVersionTriggerIsDefined(workflowVersion);-- switch (workflowVersion.trigger.type) {- case WorkflowTriggerType.DATABASE_EVENT:- await this.automatedTriggerWorkspaceService.deleteAutomatedTrigger({- workflowId: workflowVersion.workflowId,- workspaceId,- transactionScope: transactionContext?.transactionScope,- });-- return;- case WorkflowTriggerType.CRON:- await this.automatedTriggerWorkspaceService.deleteAutomatedTrigger({- workflowId: workflowVersion.workflowId,- workspaceId,- transactionScope: transactionContext?.transactionScope,- });-- const removeCronCache = async () => {- await this.cacheStorageService.hashDelete({- key: WORKFLOW_CRON_TRIGGER_CACHE_KEY,- field: workflowVersion.workflowId,- });- };-- if (isDefined(transactionContext)) {- transactionContext.transactionScope.afterCommit(removeCronCache);- } else {- await removeCronCache();- }-- return;- case WorkflowTriggerType.MANUAL:- case WorkflowTriggerType.WEBHOOK:- return;- default:- assertNever(workflowVersion.trigger);- }- }-- private async emitStatusUpdateEvents(- workflowVersion: WorkflowVersionWorkspaceEntity,- newStatus: WorkflowVersionStatus,- workspaceId: string,- ) {- this.workspaceEventEmitter.emitCustomBatchEvent<WorkflowVersionStatusUpdate>(- WORKFLOW_VERSION_STATUS_UPDATED,- [- {- workflowId: workflowVersion.workflowId,- workflowVersionId: workflowVersion.id,- previousStatus: workflowVersion.status,- newStatus,- },- ],- workspaceId,- );- }-}