The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
feat(workflow): discard a workflow draft through the core API (#25902)
Thomas Trompette8e106f7238ed
diff --git a/packages/twenty-front/src/generated/graphql.ts b/packages/twenty-front/src/generated/graphql.tsindex a2fa9b030cf..3d3374503a6 100644--- a/packages/twenty-front/src/generated/graphql.ts+++ b/packages/twenty-front/src/generated/graphql.ts@@ -222,6 +222,10 @@ export type DeletedCoreWorkflowDto = {workspaceWorkflowId: Scalars['UUID']['output'];};+export type DiscardCoreWorkflowDraftInput = {+ workspaceWorkflowVersionId: Scalars['UUID']['input'];+};+export type DpaAgreement = {__typename?: 'DpaAgreement';acceptedAt: Scalars['DateTime']['output'];@@ -336,6 +340,7 @@ export type Mutation = {deleteCoreWorkflows: Array<DeletedCoreWorkflowDto>;deleteWorkflowVersionEdge: WorkflowVersionStepChanges;deleteWorkflowVersionStep: WorkflowVersionStepChanges;+ discardCoreWorkflowDraft?: Maybe<CoreWorkflowDto>;dismissMaintenanceModeBanner: Scalars['Boolean']['output'];dismissReconnectAccountBanner: Scalars['Boolean']['output'];duplicateWorkflow: WorkflowVersionDto;@@ -403,6 +408,11 @@ export type MutationDeleteWorkflowVersionStepArgs = {};+export type MutationDiscardCoreWorkflowDraftArgs = {+ input: DiscardCoreWorkflowDraftInput;+};++export type MutationDismissReconnectAccountBannerArgs = {connectedAccountId: Scalars['UUID']['input'];};@@ -960,6 +970,13 @@ export type DeleteCoreWorkflowsMutationVariables = Exact<{export type DeleteCoreWorkflowsMutation = { __typename?: 'Mutation', deleteCoreWorkflows: Array<{ __typename?: 'DeletedCoreWorkflowDTO', id: any, workspaceWorkflowId: any }> };+export type DiscardCoreWorkflowDraftMutationVariables = Exact<{+ input: DiscardCoreWorkflowDraftInput;+}>;+++export type DiscardCoreWorkflowDraftMutation = { __typename?: 'Mutation', discardCoreWorkflowDraft?: { __typename?: 'CoreWorkflowDTO', id: any, name?: string | null, statuses: Array<CoreWorkflowStatus>, lastPublishedVersionId?: any | null, workspaceWorkflowId?: any | null, updatedAt: string } | null };+export type GetCoreWorkflowQueryVariables = Exact<{workspaceWorkflowId: Scalars['UUID']['input'];}>;@@ -1154,6 +1171,7 @@ export const GetTimelineThreadsFromObjectRecordDocument = {"kind":"Document","deexport const SearchDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"Search"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"limit"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"excludedObjectNameSingulars"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"includedObjectNameSingulars"}},"type":{"kind":"ListType","type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"filter"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"ObjectRecordFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"search"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"searchInput"},"value":{"kind":"Variable","name":{"kind":"Name","value":"searchInput"}}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"Variable","name":{"kind":"Name","value":"limit"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"excludedObjectNameSingulars"},"value":{"kind":"Variable","name":{"kind":"Name","value":"excludedObjectNameSingulars"}}},{"kind":"Argument","name":{"kind":"Name","value":"includedObjectNameSingulars"},"value":{"kind":"Variable","name":{"kind":"Name","value":"includedObjectNameSingulars"}}},{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"Variable","name":{"kind":"Name","value":"filter"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recordId"}},{"kind":"Field","name":{"kind":"Name","value":"objectNameSingular"}},{"kind":"Field","name":{"kind":"Name","value":"objectLabelSingular"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"imageUrl"}},{"kind":"Field","name":{"kind":"Name","value":"tsRankCD"}},{"kind":"Field","name":{"kind":"Name","value":"tsRank"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}},{"kind":"Field","name":{"kind":"Name","value":"endCursor"}}]}}]}}]}}]} as unknown as DocumentNode<SearchQuery, SearchQueryVariables>;export const CreateCoreWorkflowDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateCoreWorkflow"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateCoreWorkflowInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createCoreWorkflow"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<CreateCoreWorkflowMutation, CreateCoreWorkflowMutationVariables>;export const DeleteCoreWorkflowsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteCoreWorkflows"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"DeleteCoreWorkflowsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteCoreWorkflows"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}}]}}]}}]} as unknown as DocumentNode<DeleteCoreWorkflowsMutation, DeleteCoreWorkflowsMutationVariables>;+export const DiscardCoreWorkflowDraftDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DiscardCoreWorkflowDraft"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"DiscardCoreWorkflowDraftInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"discardCoreWorkflowDraft"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"lastPublishedVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<DiscardCoreWorkflowDraftMutation, DiscardCoreWorkflowDraftMutationVariables>;export const GetCoreWorkflowDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflow"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflow"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceWorkflowId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"lastPublishedVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowQuery, GetCoreWorkflowQueryVariables>;export const GetCoreWorkflowsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflows"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"first"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"after"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"orderBy"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowOrderByField"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"orderByDirection"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowOrderByDirection"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"filter"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"CoreWorkflowFilterInput"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflows"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"first"},"value":{"kind":"Variable","name":{"kind":"Name","value":"first"}}},{"kind":"Argument","name":{"kind":"Name","value":"after"},"value":{"kind":"Variable","name":{"kind":"Name","value":"after"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderBy"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderBy"}}},{"kind":"Argument","name":{"kind":"Name","value":"orderByDirection"},"value":{"kind":"Variable","name":{"kind":"Name","value":"orderByDirection"}}},{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"Variable","name":{"kind":"Name","value":"filter"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"edges"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"node"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"statuses"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cursor"}}]}},{"kind":"Field","name":{"kind":"Name","value":"pageInfo"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"endCursor"}},{"kind":"Field","name":{"kind":"Name","value":"hasNextPage"}}]}},{"kind":"Field","name":{"kind":"Name","value":"totalCount"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowsQuery, GetCoreWorkflowsQueryVariables>;export const GetCoreWorkflowVersionDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetCoreWorkflowVersion"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"coreWorkflowVersion"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceWorkflowVersionId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"label"}},{"kind":"Field","name":{"kind":"Name","value":"status"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowVersionId"}},{"kind":"Field","name":{"kind":"Name","value":"workspaceWorkflowId"}},{"kind":"Field","name":{"kind":"Name","value":"trigger"}},{"kind":"Field","name":{"kind":"Name","value":"steps"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<GetCoreWorkflowVersionQuery, GetCoreWorkflowVersionQueryVariables>;diff --git a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/workflow/components/DiscardDraftWorkflowSingleRecordCommand.tsx b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/workflow/components/DiscardDraftWorkflowSingleRecordCommand.tsxindex 6f9e2ace891..6d6e773bd12 100644--- a/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/workflow/components/DiscardDraftWorkflowSingleRecordCommand.tsx+++ b/packages/twenty-front/src/modules/command-menu-item/engine-command/record/single-record/workflow/components/DiscardDraftWorkflowSingleRecordCommand.tsx@@ -1,14 +1,15 @@+import { isDefined } from 'twenty-shared/utils';+import { HeadlessEngineCommandWrapperEffect } from '@/command-menu-item/engine-command/components/HeadlessEngineCommandWrapperEffect';import { useHeadlessCommandContextApi } from '@/command-menu-item/engine-command/hooks/useHeadlessCommandContextApi';-import { useDeleteOneWorkflowVersion } from '@/workflow/hooks/useDeleteOneWorkflowVersion';+import { useDiscardCoreWorkflowDraft } from '@/object-core/workflows/hooks/useDiscardCoreWorkflowDraft';import { useWorkflowWithCurrentVersion } from '@/workflow/hooks/useWorkflowWithCurrentVersion';-import { isDefined } from 'twenty-shared/utils';export const DiscardDraftWorkflowSingleRecordCommand = () => {const { selectedRecords } = useHeadlessCommandContextApi();const recordId = selectedRecords[0]?.id;- const { deleteOneWorkflowVersion } = useDeleteOneWorkflowVersion();+ const { discardCoreWorkflowDraft } = useDiscardCoreWorkflowDraft();const workflowWithCurrentVersion = useWorkflowWithCurrentVersion(recordId ?? '',);@@ -22,8 +23,8 @@ export const DiscardDraftWorkflowSingleRecordCommand = () => {return;}- deleteOneWorkflowVersion({- workflowVersionId: workflowWithCurrentVersion.currentVersion.id,+ return discardCoreWorkflowDraft({+ workspaceWorkflowVersionId: workflowWithCurrentVersion.currentVersion.id,});};diff --git a/packages/twenty-front/src/modules/object-core/workflows/graphql/mutations/discardCoreWorkflowDraft.ts b/packages/twenty-front/src/modules/object-core/workflows/graphql/mutations/discardCoreWorkflowDraft.tsnew file mode 100644index 00000000000..56c04a6813c--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/workflows/graphql/mutations/discardCoreWorkflowDraft.ts@@ -0,0 +1,14 @@+import { gql } from '@apollo/client';++export const DISCARD_CORE_WORKFLOW_DRAFT = gql`+ mutation DiscardCoreWorkflowDraft($input: DiscardCoreWorkflowDraftInput!) {+ discardCoreWorkflowDraft(input: $input) {+ id+ name+ statuses+ lastPublishedVersionId+ workspaceWorkflowId+ updatedAt+ }+ }+`;diff --git a/packages/twenty-front/src/modules/object-core/workflows/hooks/useDiscardCoreWorkflowDraft.ts b/packages/twenty-front/src/modules/object-core/workflows/hooks/useDiscardCoreWorkflowDraft.tsnew file mode 100644index 00000000000..fc41179ff32--- /dev/null+++ b/packages/twenty-front/src/modules/object-core/workflows/hooks/useDiscardCoreWorkflowDraft.ts@@ -0,0 +1,37 @@+import { useMutation } from '@apollo/client/react';++import { DISCARD_CORE_WORKFLOW_DRAFT } from '@/object-core/workflows/graphql/mutations/discardCoreWorkflowDraft';+import { invalidateCoreWorkflowVersions } from '@/object-core/workflows/versions/utils/invalidateCoreWorkflowVersions';+import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';+import { useEvictDiscardedDraftFromWorkflowCache } from '@/workflow/hooks/useEvictDiscardedDraftFromWorkflowCache';+import {+ type DiscardCoreWorkflowDraftMutation,+ type DiscardCoreWorkflowDraftMutationVariables,+} from '~/generated/graphql';++export const useDiscardCoreWorkflowDraft = () => {+ const apolloCoreClient = useApolloCoreClient();+ const { evictDiscardedDraftFromWorkflowCache } =+ useEvictDiscardedDraftFromWorkflowCache();++ const [discardCoreWorkflowDraftMutation] = useMutation<+ DiscardCoreWorkflowDraftMutation,+ DiscardCoreWorkflowDraftMutationVariables+ >(DISCARD_CORE_WORKFLOW_DRAFT, { client: apolloCoreClient });++ const discardCoreWorkflowDraft = async ({+ workspaceWorkflowVersionId,+ }: {+ workspaceWorkflowVersionId: string;+ }) => {+ await discardCoreWorkflowDraftMutation({+ variables: { input: { workspaceWorkflowVersionId } },+ });++ evictDiscardedDraftFromWorkflowCache(workspaceWorkflowVersionId);++ await invalidateCoreWorkflowVersions(apolloCoreClient);+ };++ return { discardCoreWorkflowDraft };+};diff --git a/packages/twenty-front/src/modules/workflow/hooks/useDeleteOneWorkflowVersion.ts b/packages/twenty-front/src/modules/workflow/hooks/useEvictDiscardedDraftFromWorkflowCache.tssimilarity index 78%rename from packages/twenty-front/src/modules/workflow/hooks/useDeleteOneWorkflowVersion.tsrename to packages/twenty-front/src/modules/workflow/hooks/useEvictDiscardedDraftFromWorkflowCache.tsindex 6cfe9a1f9c0..667f24a354d 100644--- a/packages/twenty-front/src/modules/workflow/hooks/useDeleteOneWorkflowVersion.ts+++ b/packages/twenty-front/src/modules/workflow/hooks/useEvictDiscardedDraftFromWorkflowCache.ts@@ -1,4 +1,3 @@-import { invalidateCoreWorkflowVersions } from '@/object-core/workflows/versions/utils/invalidateCoreWorkflowVersions';import { useCallback } from 'react';import { useApolloCoreClient } from '@/object-metadata/hooks/useApolloCoreClient';@@ -6,12 +5,11 @@ import { useObjectMetadataItem } from '@/object-metadata/hooks/useObjectMetadataimport { CoreObjectNameSingular } from 'twenty-shared/types';import { useGetRecordFromCache } from '@/object-record/cache/hooks/useGetRecordFromCache';import { modifyRecordFromCache } from '@/object-record/cache/utils/modifyRecordFromCache';-import { useDeleteOneRecord } from '@/object-record/hooks/useDeleteOneRecord';import { useUpsertRecordsInStore } from '@/object-record/record-store/hooks/useUpsertRecordsInStore';import { type Workflow, type WorkflowVersion } from '@/workflow/types/Workflow';import { isDefined } from 'twenty-shared/utils';-export const useDeleteOneWorkflowVersion = () => {+export const useEvictDiscardedDraftFromWorkflowCache = () => {const apolloCoreClient = useApolloCoreClient();const getWorkflowVersionFromCache = useGetRecordFromCache({objectNameSingular: CoreObjectNameSingular.WorkflowVersion,@@ -23,9 +21,13 @@ export const useDeleteOneWorkflowVersion = () => {useObjectMetadataItem({objectNameSingular: CoreObjectNameSingular.Workflow,});+ const { objectMetadataItem: objectMetadataItemWorkflowVersion } =+ useObjectMetadataItem({+ objectNameSingular: CoreObjectNameSingular.WorkflowVersion,+ });const { upsertRecordsInStore } = useUpsertRecordsInStore();- const handleUpdate = useCallback(+ const evictDiscardedDraftFromWorkflowCache = useCallback((workflowVersionId: string) => {if (!workflowVersionId) {return;@@ -40,6 +42,21 @@ export const useDeleteOneWorkflowVersion = () => {return;}+ const discardedAt = new Date().toISOString();++ modifyRecordFromCache({+ objectMetadataItem: objectMetadataItemWorkflowVersion,+ cache,+ recordId: workflowVersionId,+ fieldModifiers: {+ deletedAt: () => discardedAt,+ },+ });++ upsertRecordsInStore({+ partialRecords: [{ ...cachedWorkflowVersion, deletedAt: discardedAt }],+ });+const cachedWorkflow = getWorkflowFromCache<Workflow>(cachedWorkflowVersion.workflowId,);@@ -86,24 +103,10 @@ export const useDeleteOneWorkflowVersion = () => {getWorkflowFromCache,getWorkflowVersionFromCache,objectMetadataItemWorkflow,+ objectMetadataItemWorkflowVersion,upsertRecordsInStore,],);- const { deleteOneRecord } = useDeleteOneRecord({- objectNameSingular: CoreObjectNameSingular.WorkflowVersion,- });-- const deleteOneWorkflowVersion = async ({- workflowVersionId,- }: {- workflowVersionId: string;- }) => {- await deleteOneRecord(workflowVersionId);- handleUpdate(workflowVersionId);-- await invalidateCoreWorkflowVersions(apolloCoreClient);- };-- return { deleteOneWorkflowVersion };+ return { evictDiscardedDraftFromWorkflowCache };};diff --git a/packages/twenty-server/src/engine/core-modules/workflow/dtos/discard-core-workflow-draft.input.ts b/packages/twenty-server/src/engine/core-modules/workflow/dtos/discard-core-workflow-draft.input.tsnew file mode 100644index 00000000000..2bed2a62751--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/dtos/discard-core-workflow-draft.input.ts@@ -0,0 +1,12 @@+import { Field, InputType } from '@nestjs/graphql';++import { IsUUID } from 'class-validator';++import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';++@InputType()+export class DiscardCoreWorkflowDraftInput {+ @Field(() => UUIDScalarType)+ @IsUUID()+ workspaceWorkflowVersionId: string;+}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/filters/workflow-query-validation-graphql-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/workflow/filters/workflow-query-validation-graphql-api-exception.filter.tsnew file mode 100644index 00000000000..57c8d551c67--- /dev/null+++ b/packages/twenty-server/src/engine/core-modules/workflow/filters/workflow-query-validation-graphql-api-exception.filter.ts@@ -0,0 +1,28 @@+import { Catch, type ExceptionFilter } from '@nestjs/common';++import { assertUnreachable } from 'twenty-shared/utils';++import { ForbiddenError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';+import {+ WorkflowQueryValidationException,+ WorkflowQueryValidationExceptionCode,+} from 'src/modules/workflow/common/exceptions/workflow-query-validation.exception';++export const handleWorkflowQueryValidationException = (+ exception: WorkflowQueryValidationException,+) => {+ switch (exception.code) {+ case WorkflowQueryValidationExceptionCode.FORBIDDEN:+ throw new ForbiddenError(exception);+ default: {+ assertUnreachable(exception.code);+ }+ }+};++@Catch(WorkflowQueryValidationException)+export class WorkflowQueryValidationGraphqlApiExceptionFilter implements ExceptionFilter {+ catch(exception: WorkflowQueryValidationException) {+ handleWorkflowQueryValidationException(exception);+ }+}diff --git a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.tsindex 383e3cf78b0..7f7cfc8a8b0 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/resolvers/core-workflow.resolver.ts@@ -11,6 +11,8 @@ import { CoreWorkflowDTO } from 'src/engine/core-modules/workflow/dtos/core-workimport { CreateCoreWorkflowInput } from 'src/engine/core-modules/workflow/dtos/create-core-workflow.input';import { DeletedCoreWorkflowDTO } from 'src/engine/core-modules/workflow/dtos/deleted-core-workflow.dto';import { DeleteCoreWorkflowsInput } from 'src/engine/core-modules/workflow/dtos/delete-core-workflows.input';+import { DiscardCoreWorkflowDraftInput } from 'src/engine/core-modules/workflow/dtos/discard-core-workflow-draft.input';+import { WorkflowQueryValidationGraphqlApiExceptionFilter } from 'src/engine/core-modules/workflow/filters/workflow-query-validation-graphql-api-exception.filter';import { CoreWorkflowVersionDTO } from 'src/engine/core-modules/workflow/dtos/core-workflow-version.dto';import { CoreWorkflowVersionArgs } from 'src/engine/core-modules/workflow/dtos/core-workflow-version.input';import { CoreWorkflowVersionsArgs } from 'src/engine/core-modules/workflow/dtos/core-workflow-versions.input';@@ -22,6 +24,8 @@ import { CoreWorkflowVersionListService } from 'src/engine/core-modules/workflowimport { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';import { AuthUser } from 'src/engine/decorators/auth/auth-user.decorator';+import { isDefined } from 'twenty-shared/utils';+import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';import { UserAuthGuard } from 'src/engine/guards/user-auth.guard';@@ -36,6 +40,7 @@ import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-moduleSettingsPermissionGuard(PermissionFlagType.WORKFLOWS),)@UseFilters(+ WorkflowQueryValidationGraphqlApiExceptionFilter,PermissionsGraphqlApiExceptionFilter,PreventNestToAutoLogGraphqlErrorsFilter,)@@ -70,6 +75,27 @@ export class CoreWorkflowResolver {);}+ @Mutation(() => CoreWorkflowDTO, { nullable: true })+ async discardCoreWorkflowDraft(+ @AuthWorkspace() { id: workspaceId }: WorkspaceEntity,+ @Args('input') input: DiscardCoreWorkflowDraftInput,+ ): Promise<CoreWorkflowDTO | null> {+ const workspaceWorkflowId =+ await this.coreWorkflowMutationWorkspaceService.discardDraftVersion(+ workspaceId,+ input,+ );++ if (!isDefined(workspaceWorkflowId)) {+ return null;+ }++ return this.coreWorkflowListService.findOneByWorkspaceWorkflowId({+ workspaceId,+ workspaceWorkflowId,+ });+ }+@Query(() => CoreWorkflowConnectionDTO)async coreWorkflows(@AuthWorkspace() { id: workspaceId }: WorkspaceEntity,diff --git a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.tsindex aa6438bb983..f4e83167b3c 100644--- a/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts+++ b/packages/twenty-server/src/engine/core-modules/workflow/services/core-workflow-mutation.workspace-service.ts@@ -1,6 +1,7 @@import { Injectable, Logger } from '@nestjs/common';-import { In } from 'typeorm';+import { In, IsNull, Not } from 'typeorm';+import { msg } from '@lingui/core/macro';import { isDefined } from 'twenty-shared/utils';import { v4 as uuidv4 } from 'uuid';@@ -16,7 +17,15 @@ import { buildSystemAuthContext } from 'src/engine/twenty-orm/utils/build-systemimport { WorkspaceOrmManager } from 'src/engine/twenty-orm/workspace-orm.manager';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 WorkflowVersionWorkspaceEntity } from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';+import {+ WorkflowQueryValidationException,+ WorkflowQueryValidationExceptionCode,+} from 'src/modules/workflow/common/exceptions/workflow-query-validation.exception';+import { assertWorkflowVersionIsDraft } from 'src/modules/workflow/common/utils/assert-workflow-version-is-draft.util';+import {+ WorkflowVersionStatus,+ type WorkflowVersionWorkspaceEntity,+} from 'src/modules/workflow/common/standard-objects/workflow-version.workspace-entity';import {WorkflowStatus,type WorkflowWorkspaceEntity,@@ -24,6 +33,11 @@ import {import { WorkflowCommonWorkspaceService } from 'src/modules/workflow/common/workspace-services/workflow-common.workspace-service';import { type WorkspaceMemberWorkspaceEntity } from 'src/modules/workspace-member/standard-objects/workspace-member.workspace-entity';+type DiscardDraftVersionOutcome =+ | { status: 'versionNotFound' }+ | { status: 'alreadyDiscarded' }+ | { status: 'discarded'; workflowId: string };+@Injectable()export class CoreWorkflowMutationWorkspaceService {private readonly logger = new Logger(@@ -199,6 +213,87 @@ export class CoreWorkflowMutationWorkspaceService {.filter(isDefined);}+ async discardDraftVersion(+ workspaceId: string,+ { workspaceWorkflowVersionId }: { workspaceWorkflowVersionId: string },+ ): Promise<string | null> {+ const authContext = buildSystemAuthContext(workspaceId);++ const outcome: DiscardDraftVersionOutcome =+ await this.workspaceOrmManager.executeInWorkspaceContext(async () => {+ const workflowVersionRepository =+ this.workspaceOrmManager.getRepository<WorkflowVersionWorkspaceEntity>(+ 'workflowVersion',+ { shouldBypassPermissionChecks: true },+ );++ const version = await workflowVersionRepository.findOne({+ where: { id: workspaceWorkflowVersionId },+ withDeleted: true,+ });++ if (!isDefined(version)) {+ return { status: 'versionNotFound' };+ }++ if (isDefined(version.deletedAt)) {+ return { status: 'alreadyDiscarded' };+ }++ assertWorkflowVersionIsDraft(version);++ const otherLiveVersionsExist = await workflowVersionRepository.exists({+ where: {+ workflowId: version.workflowId,+ deletedAt: IsNull(),+ id: Not(workspaceWorkflowVersionId),+ },+ });++ if (!otherLiveVersionsExist) {+ throw new WorkflowQueryValidationException(+ 'The initial version of a workflow can not be deleted',+ WorkflowQueryValidationExceptionCode.FORBIDDEN,+ {+ userFriendlyMessage: msg`The initial version of a workflow can not be deleted`,+ },+ );+ }++ const softDeleteResult = await workflowVersionRepository.softDelete({+ id: workspaceWorkflowVersionId,+ status: WorkflowVersionStatus.DRAFT,+ });++ if (softDeleteResult.affected === 0) {+ throw new WorkflowQueryValidationException(+ 'Workflow version is not in draft status',+ WorkflowQueryValidationExceptionCode.FORBIDDEN,+ {+ userFriendlyMessage: msg`Workflow version is not in draft status`,+ },+ );+ }++ return { status: 'discarded', workflowId: version.workflowId };+ }, authContext);++ if (outcome.status === 'versionNotFound') {+ return null;+ }++ await this.workflowVersionCoreSyncService.deleteCoreVersionsByWorkspaceVersionIds(+ workspaceId,+ [workspaceWorkflowVersionId],+ );++ if (outcome.status === 'alreadyDiscarded') {+ return null;+ }++ return outcome.workflowId;+ }+private async rollbackCreatedWorkflow(workspaceId: string,coreWorkflowId: string,diff --git a/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-discard-draft.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-discard-draft.integration-spec.tsnew file mode 100644index 00000000000..2cff2e10162--- /dev/null+++ b/packages/twenty-server/test/integration/graphql/suites/workflow/core-workflow-discard-draft.integration-spec.ts@@ -0,0 +1,234 @@+import { updateWorkflowVersionTrigger } from 'test/integration/graphql/suites/workflow/utils/update-workflow-version-trigger.util';+import { workflowGraphqlRequest } from 'test/integration/graphql/suites/workflow/utils/workflow-graphql-request.util';+import { isDefined } from 'twenty-shared/utils';++import { getWorkspaceSchemaName } from 'src/engine/workspace-datasource/utils/get-workspace-schema-name.util';+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';++const WORKSPACE_SCHEMA = getWorkspaceSchemaName(SEED_APPLE_WORKSPACE_ID);++const DISCARD_MUTATION = `+ mutation Discard($input: DiscardCoreWorkflowDraftInput!) {+ discardCoreWorkflowDraft(input: $input) {+ id+ statuses+ }+ }+`;++describe('discardCoreWorkflowDraft (e2e)', () => {+ let coreWorkflowId: string;+ let workspaceWorkflowId: string;+ let initialWorkspaceVersionId: string;+ let draftWorkspaceVersionId: string;++ beforeAll(async () => {+ const createResponse = await workflowGraphqlRequest(`+ mutation {+ createCoreWorkflow(input: { name: "Discard Draft Target" }) {+ id+ workspaceWorkflowId+ }+ }+ `);++ expect(createResponse.body.errors).toBeUndefined();++ coreWorkflowId = createResponse.body.data.createCoreWorkflow.id;+ workspaceWorkflowId =+ createResponse.body.data.createCoreWorkflow.workspaceWorkflowId;++ const versionsResponse = await workflowGraphqlRequest(+ `+ query GetWorkflow($id: UUID!) {+ workflow(filter: { id: { eq: $id } }) {+ versions {+ edges {+ node {+ id+ }+ }+ }+ }+ }+ `,+ { id: workspaceWorkflowId },+ );++ initialWorkspaceVersionId =+ versionsResponse.body.data.workflow.versions.edges[0].node.id;++ await updateWorkflowVersionTrigger({+ workflowVersionId: initialWorkspaceVersionId,+ trigger: {+ name: 'Manual Trigger',+ type: 'MANUAL',+ settings: { outputSchema: {} },+ nextStepIds: [],+ position: { x: 0, y: 0 },+ },+ });++ const stepResponse = await workflowGraphqlRequest(+ `+ mutation CreateWorkflowVersionStep(+ $input: CreateWorkflowVersionStepInput!+ ) {+ createWorkflowVersionStep(input: $input) {+ stepsDiff+ }+ }+ `,+ {+ input: {+ workflowVersionId: initialWorkspaceVersionId,+ stepType: 'FIND_RECORDS',+ parentStepId: 'trigger',+ position: { x: 200, y: 0 },+ },+ },+ );++ expect(stepResponse.body.errors).toBeUndefined();++ const activateResponse = await workflowGraphqlRequest(+ `+ mutation ActivateWorkflowVersion($workflowVersionId: UUID!) {+ activateWorkflowVersion(workflowVersionId: $workflowVersionId)+ }+ `,+ { workflowVersionId: initialWorkspaceVersionId },+ );++ expect(activateResponse.body.errors).toBeUndefined();++ const draftResponse = await workflowGraphqlRequest(+ `+ mutation CreateDraft($input: CreateDraftFromWorkflowVersionInput!) {+ createDraftFromWorkflowVersion(input: $input) {+ id+ }+ }+ `,+ {+ input: {+ workflowId: workspaceWorkflowId,+ workflowVersionIdToCopy: initialWorkspaceVersionId,+ },+ },+ );++ expect(draftResponse.body.errors).toBeUndefined();+ draftWorkspaceVersionId =+ draftResponse.body.data.createDraftFromWorkflowVersion.id;+ });++ afterAll(async () => {+ if (isDefined(workspaceWorkflowId)) {+ await workflowGraphqlRequest(+ `+ mutation DestroyWorkflow($id: ID!) {+ destroyWorkflow(id: $id) {+ id+ }+ }+ `,+ { id: workspaceWorkflowId },+ );+ }+ });++ it('soft-deletes the workspace draft, removes its core row and returns the refreshed workflow', async () => {+ const discardResponse = await workflowGraphqlRequest(DISCARD_MUTATION, {+ input: { workspaceWorkflowVersionId: draftWorkspaceVersionId },+ });++ expect(discardResponse.body.errors).toBeUndefined();++ const refreshedWorkflow =+ discardResponse.body.data.discardCoreWorkflowDraft;++ expect(refreshedWorkflow.id).toBe(coreWorkflowId);+ expect(refreshedWorkflow.statuses).not.toContain('DRAFT');++ const workspaceRows = await global.testDataSource.query(+ `SELECT "deletedAt" FROM "${WORKSPACE_SCHEMA}"."workflowVersion" WHERE id = $1`,+ [draftWorkspaceVersionId],+ );++ expect(workspaceRows[0]?.deletedAt).not.toBeNull();++ const coreVersionRows = await global.testDataSource.query(+ `SELECT cv.id FROM core."workflowVersion" cv+ JOIN "${WORKSPACE_SCHEMA}"."workflowVersion" wv+ ON wv."coreWorkflowVersionId" = cv.id+ WHERE cv."workspaceId" = $1 AND wv.id = $2`,+ [SEED_APPLE_WORKSPACE_ID, draftWorkspaceVersionId],+ );++ expect(coreVersionRows).toHaveLength(0);+ });++ it('returns null when the draft is already discarded', async () => {+ const discardResponse = await workflowGraphqlRequest(DISCARD_MUTATION, {+ input: { workspaceWorkflowVersionId: draftWorkspaceVersionId },+ });++ expect(discardResponse.body.errors).toBeUndefined();+ expect(discardResponse.body.data.discardCoreWorkflowDraft).toBeNull();+ });++ it('refuses to discard the only remaining version', async () => {+ const createResponse = await workflowGraphqlRequest(`+ mutation {+ createCoreWorkflow(input: { name: "Only Version Guard" }) {+ workspaceWorkflowId+ }+ }+ `);++ expect(createResponse.body.errors).toBeUndefined();++ const guardedWorkspaceWorkflowId =+ createResponse.body.data.createCoreWorkflow.workspaceWorkflowId;++ const versionsResponse = await workflowGraphqlRequest(+ `+ query GetWorkflow($id: UUID!) {+ workflow(filter: { id: { eq: $id } }) {+ versions {+ edges {+ node {+ id+ }+ }+ }+ }+ }+ `,+ { id: guardedWorkspaceWorkflowId },+ );++ const onlyVersionId =+ versionsResponse.body.data.workflow.versions.edges[0].node.id;++ const discardResponse = await workflowGraphqlRequest(DISCARD_MUTATION, {+ input: { workspaceWorkflowVersionId: onlyVersionId },+ });++ expect(discardResponse.body.errors?.[0]?.message).toContain(+ 'initial version',+ );++ await workflowGraphqlRequest(+ `+ mutation DestroyWorkflow($id: ID!) {+ destroyWorkflow(id: $id) {+ id+ }+ }+ `,+ { id: guardedWorkspaceWorkflowId },+ );+ });+});