The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Search workflow fields across steps from the root picker (#25135)
Thomas des Francsb0d51b19c8f0
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowDropdownStepOutputItems.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowDropdownStepOutputItems.tsxindex 8bb3aaa7c1e..8a3f43e152e 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowDropdownStepOutputItems.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/components/WorkflowDropdownStepOutputItems.tsx@@ -3,34 +3,24 @@ import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/Dropimport { DropdownMenuSearchInput } from '@/ui/layout/dropdown/components/DropdownMenuSearchInput';import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';-import { useGetFieldMetadataItemByIdOrThrow } from '@/object-metadata/hooks/useGetFieldMetadataItemById';import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';-import { useObjectMetadataSelectHelpers } from '@/object-metadata/hooks/useObjectMetadataSelectHelpers';-import { useGetInitialFilterValue } from '@/object-record/object-filter-dropdown/hooks/useGetInitialFilterValue';import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';import { DropdownMenuHeaderLeftComponent } from '@/ui/layout/dropdown/components/DropdownMenuHeader/internal/DropdownMenuHeaderLeftComponent';import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';-import { useWorkflowVersionIdOrThrow } from '@/workflow/hooks/useWorkflowVersionIdOrThrow';-import { stepsOutputSchemaFamilySelector } from '@/workflow/states/selectors/stepsOutputSchemaFamilySelector';-import { useUpsertStepFilterSettings } from '@/workflow/workflow-steps/filters/hooks/useUpsertStepFilterSettings';-import { getStepFilterOperands } from '@/workflow/workflow-steps/filters/utils/getStepFilterOperands';+import { WorkflowVariableSearchResultItems } from '@/workflow/workflow-variables/components/WorkflowVariableSearchResultItems';+import { useUpdateStepFilterFromVariable } from '@/workflow/workflow-steps/filters/hooks/useUpdateStepFilterFromVariable';import { useVariableDropdown } from '@/workflow/workflow-variables/hooks/useVariableDropdown';import { isRecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2';import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';+import { type WorkflowVariableSelection } from '@/workflow/workflow-variables/types/WorkflowVariableSelection';import { getCurrentSubStepFromPath } from '@/workflow/workflow-variables/utils/getCurrentSubStepFromPath';import { getStepHeaderLabel } from '@/workflow/workflow-variables/utils/getStepHeaderLabel';import { getStepItemIcon } from '@/workflow/workflow-variables/utils/getStepItemIcon';import { getVariableTemplateFromPath } from '@/workflow/workflow-variables/utils/getVariableTemplateFromPath';-import { searchVariableThroughOutputSchemaV2 } from '@/workflow/workflow-variables/utils/searchVariableThroughOutputSchemaV2';+import { getWorkflowVariableRecordObjectDisplay } from '@/workflow/workflow-variables/utils/getWorkflowVariableRecordObjectDisplay';import { useLingui } from '@lingui/react/macro';-import { useStore } from 'jotai';-import { useCallback } from 'react';-import {- type FilterableAndTSVectorFieldType,- type StepFilter,-} from 'twenty-shared/types';+import { type StepFilter } from 'twenty-shared/types';import { isDefined } from 'twenty-shared/utils';-import { extractRawVariableNamePart } from 'twenty-shared/workflow';import { IconChevronLeft, useIcons } from 'twenty-ui/icon';import { OverflowingTextWithTooltip } from 'twenty-ui/surfaces';import { MenuItemSelect } from 'twenty-ui/navigation';@@ -38,6 +28,7 @@ import { MenuItemSelect } from 'twenty-ui/navigation';type WorkflowDropdownStepOutputItemsProps = {stepFilter: StepFilter;step: StepOutputSchemaV2;+ initialPath?: string[];onSelect: () => void;onBack: () => void;};@@ -45,101 +36,26 @@ type WorkflowDropdownStepOutputItemsProps = {export const WorkflowDropdownStepOutputItems = ({stepFilter,step,+ initialPath,onSelect,onBack,}: WorkflowDropdownStepOutputItemsProps) => {const { t } = useLingui();const { getIcon } = useIcons();- const { getSelectIconPropsFromObjectMetadataItem } =- useObjectMetadataSelectHelpers();- const { upsertStepFilterSettings } = useUpsertStepFilterSettings();- const { getFieldMetadataItemByIdOrThrow } =- useGetFieldMetadataItemByIdOrThrow();-- const workflowVersionId = useWorkflowVersionIdOrThrow();+ const { updateStepFilterFromVariable } = useUpdateStepFilterFromVariable({+ stepFilter,+ });const { objectMetadataItems } = useObjectMetadataItems();- const { getInitialFilterValue } = useGetInitialFilterValue();-- const jotaiStore = useStore();-- const updateStepFilter = useCallback(- ({+ const handleStepFilterFieldSelect = ({+ rawVariableName,+ isFullRecord,+ }: WorkflowVariableSelection) => {+ updateStepFilterFromVariable({rawVariableName,isFullRecord,- }: {- rawVariableName: string;- isFullRecord: boolean;- }) => {- const stepId = extractRawVariableNamePart({- rawVariableName,- part: 'stepId',- });- const [currentStepOutputSchema] = jotaiStore.get(- stepsOutputSchemaFamilySelector.selectorFamily({- workflowVersionId,- stepIds: [stepId],- }),- );-- const { variableType, fieldMetadataId, compositeFieldSubFieldName } =- searchVariableThroughOutputSchemaV2({- stepOutputSchema: currentStepOutputSchema,- stepType: step.type,- rawVariableName,- isFullRecord: false,- });-- const { fieldMetadataItem: filterFieldMetadataItem } = isDefined(- fieldMetadataId,- )- ? getFieldMetadataItemByIdOrThrow(fieldMetadataId)- : { fieldMetadataItem: undefined };-- const filterType = isDefined(fieldMetadataId)- ? (filterFieldMetadataItem?.type ?? 'unknown')- : variableType;-- const availableOperandsForFilter = getStepFilterOperands({- filterType,- subFieldName: compositeFieldSubFieldName,- });- const defaultOperand = availableOperandsForFilter[0];-- const { value } = getInitialFilterValue(- filterType as FilterableAndTSVectorFieldType,- defaultOperand,- );-- upsertStepFilterSettings({- stepFilterToUpsert: {- ...stepFilter,- stepOutputKey: rawVariableName,- isFullRecord,- type: filterType ?? 'unknown',- value: value,- fieldMetadataId,- compositeFieldSubFieldName,- operand: defaultOperand,- },- });- },- [- jotaiStore,- workflowVersionId,- step.type,- getFieldMetadataItemByIdOrThrow,- upsertStepFilterSettings,- stepFilter,- getInitialFilterValue,- ],- );-- const handleStepFilterFieldSelect = (key: string) => {- updateStepFilter({- rawVariableName: key,- isFullRecord: false,+ stepType: step.type,});onSelect();};@@ -149,12 +65,18 @@ export const WorkflowDropdownStepOutputItems = ({setSearchInputValue,handleSelectField,goBack,- filteredOptions,+ options,currentPath,+ isSearching,+ searchResults,+ handleSelectSearchResult,} = useVariableDropdown({step,+ initialPath,onSelect: handleStepFilterFieldSelect,onBack,+ shouldDisplaySpecialItems: false,+ shouldDisplayRecordObjects: true,});const getDisplayedSubStepObject = () => {@@ -174,12 +96,13 @@ export const WorkflowDropdownStepOutputItems = ({return;}- updateStepFilter({+ updateStepFilterFromVariable({rawVariableName: getVariableTemplateFromPath({stepId: step.id,path: [...currentPath, currentSubStep.object.fieldIdName ?? 'id'],}),isFullRecord: true,+ stepType: step.type,});onSelect();};@@ -194,19 +117,16 @@ export const WorkflowDropdownStepOutputItems = ({): undefined;- const shouldDisplaySubStepObject = searchInputValue- ? isDefined(subStepObjectMetadataItem) &&- subStepObjectMetadataItem.labelSingular- .toLowerCase()- .includes(searchInputValue.toLowerCase())- : isDefined(displayedSubStepObject);-- const objectLabel = subStepObjectMetadataItem?.labelSingular;-- const subStepObjectIconProps = isDefined(subStepObjectMetadataItem)- ? getSelectIconPropsFromObjectMetadataItem(subStepObjectMetadataItem)+ const subStepObjectDisplay = isDefined(displayedSubStepObject)+ ? getWorkflowVariableRecordObjectDisplay({+ recordObject: displayedSubStepObject,+ objectMetadataItem: subStepObjectMetadataItem,+ }): undefined;+ const shouldDisplaySubStepObject =+ subStepObjectDisplay?.isSelectable === true;+return (<DropdownContent widthInPixels={GenericDropdownContentWidth.ExtraLarge}><DropdownMenuHeader@@ -228,49 +148,62 @@ export const WorkflowDropdownStepOutputItems = ({/><DropdownMenuSeparator /><DropdownMenuItemsContainer hasMaxHeight>- {shouldDisplaySubStepObject && (- <MenuItemSelect- selected={false}- focused={false}- onClick={handleSelectObject}- text={objectLabel || ''}- hasSubMenu={false}- LeftIcon={subStepObjectIconProps?.Icon}- leftIconColor={subStepObjectIconProps?.iconThemeColor}- contextualText={t`Pick a ${objectLabel} record`}+ {isSearching ? (+ <WorkflowVariableSearchResultItems+ searchResults={searchResults}+ onSelect={handleSelectSearchResult}/>- )}- {filteredOptions.length > 0 && shouldDisplaySubStepObject && (- <DropdownMenuSeparator />- )}- {filteredOptions.map(([key, subStep]) => {- if (!isDefined(subStep)) {- return null;- }-- return (- <MenuItemSelect- key={key}- selected={false}- focused={false}- onClick={() => handleSelectField(key)}- text={subStep.label || key}- hasSubMenu={!subStep.isLeaf}- LeftIcon={- subStep.icon- ? getIcon(subStep.icon)- : getIcon(- getStepItemIcon({- itemType: subStep.type,- }),- )- }- contextualText={- subStep.isLeaf ? subStep?.value?.toString() : undefined+ ) : (+ <>+ {shouldDisplaySubStepObject && (+ <MenuItemSelect+ selected={false}+ focused={false}+ onClick={handleSelectObject}+ text={subStepObjectDisplay?.label ?? ''}+ hasSubMenu={false}+ LeftIcon={+ isDefined(subStepObjectDisplay?.icon)+ ? getIcon(subStepObjectDisplay.icon)+ : undefined+ }+ leftIconColor={subStepObjectDisplay?.iconColor}+ contextualText={t`Pick a ${subStepObjectDisplay?.label} record`}+ />+ )}+ {options.length > 0 && shouldDisplaySubStepObject && (+ <DropdownMenuSeparator />+ )}+ {options.map(([key, subStep]) => {+ if (!isDefined(subStep)) {+ return null;}- />- );- })}++ return (+ <MenuItemSelect+ key={key}+ selected={false}+ focused={false}+ onClick={() => handleSelectField(key)}+ text={subStep.label || key}+ hasSubMenu={!subStep.isLeaf}+ LeftIcon={+ subStep.icon+ ? getIcon(subStep.icon)+ : getIcon(+ getStepItemIcon({+ itemType: subStep.type,+ }),+ )+ }+ contextualText={+ subStep.isLeaf ? subStep.value?.toString() : undefined+ }+ />+ );+ })}+ </>+ )}</DropdownMenuItemsContainer></DropdownContent>);diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/filters/components/WorkflowStepFilterFieldSelect.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/filters/components/WorkflowStepFilterFieldSelect.tsxindex b22bc4f8238..7a46a899c7e 100644--- a/packages/twenty-front/src/modules/workflow/workflow-steps/filters/components/WorkflowStepFilterFieldSelect.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/filters/components/WorkflowStepFilterFieldSelect.tsx@@ -5,9 +5,14 @@ import { Dropdown } from '@/ui/layout/dropdown/components/Dropdown';import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';import { WorkflowDropdownStepOutputItems } from '@/workflow/workflow-steps/components/WorkflowDropdownStepOutputItems';import { WorkflowStepFilterContext } from '@/workflow/workflow-steps/filters/states/context/WorkflowStepFilterContext';+import { useUpdateStepFilterFromVariable } from '@/workflow/workflow-steps/filters/hooks/useUpdateStepFilterFromVariable';import { WorkflowVariablesDropdownSteps } from '@/workflow/workflow-variables/components/WorkflowVariablesDropdownSteps';import { useAvailableVariablesInWorkflowStep } from '@/workflow/workflow-variables/hooks/useAvailableVariablesInWorkflowStep';import { useSearchVariable } from '@/workflow/workflow-variables/hooks/useSearchVariable';+import {+ type WorkflowVariableSelection,+ type WorkflowVariableStepSelection,+} from '@/workflow/workflow-variables/types/WorkflowVariableSelection';import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';import { useLingui } from '@lingui/react/macro';@@ -41,6 +46,9 @@ export const WorkflowStepFilterFieldSelect = ({);const { t } = useLingui();const { closeDropdown } = useCloseDropdown();+ const { updateStepFilterFromVariable } = useUpdateStepFilterFromVariable({+ stepFilter,+ });const { getIcon } = useIcons();const { getSelectIconPropsFromObjectMetadataItem } =useObjectMetadataSelectHelpers();@@ -60,6 +68,7 @@ export const WorkflowStepFilterFieldSelect = ({const [selectedStep, setSelectedStep] = useState<StepOutputSchemaV2 | undefined>(initialStep);+ const [selectedPath, setSelectedPath] = useState<string[]>([]);const stepId = extractRawVariableNamePart({rawVariableName: stepFilter.stepOutputKey,@@ -79,7 +88,11 @@ export const WorkflowStepFilterFieldSelect = ({const dropdownId = `step-filter-field-${stepFilter.id}`;- const handleStepSelect = (stepId: string) => {+ const handleStepSelect = ({+ stepId,+ path = [],+ }: WorkflowVariableStepSelection) => {+ setSelectedPath(path);setSelectedStep(availableVariablesInWorkflowStep.find((step) => step.id === stepId),);@@ -87,6 +100,7 @@ export const WorkflowStepFilterFieldSelect = ({const handleSubItemSelect = () => {setSelectedStep(initialStep);+ setSelectedPath([]);closeDropdown(dropdownId);};@@ -94,6 +108,27 @@ export const WorkflowStepFilterFieldSelect = ({setSelectedStep(undefined);};+ const handleVariableSelect = ({+ rawVariableName,+ stepId,+ isFullRecord,+ }: WorkflowVariableSelection) => {+ const step = availableVariablesInWorkflowStep.find(+ (item) => item.id === stepId,+ );++ if (!isDefined(step)) {+ return;+ }++ updateStepFilterFromVariable({+ rawVariableName,+ stepType: step.type,+ isFullRecord,+ });+ handleSubItemSelect();+ };+const isSelectedFieldNotFound = !isDefined(variableLabel);const isStepOutputKeyBroken =@@ -177,11 +212,15 @@ export const WorkflowStepFilterFieldSelect = ({dropdownId={dropdownId}steps={availableVariablesInWorkflowStep}onSelect={handleStepSelect}+ onVariableSelect={handleVariableSelect}+ shouldDisplaySpecialItems={false}+ shouldDisplayRecordObjects/>) : (<WorkflowDropdownStepOutputItemsstepFilter={stepFilter}step={selectedStep}+ initialPath={selectedPath}onSelect={handleSubItemSelect}onBack={handleBack}/>diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/filters/hooks/useUpdateStepFilterFromVariable.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/filters/hooks/useUpdateStepFilterFromVariable.tsnew file mode 100644index 00000000000..e0b16d539d1--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/filters/hooks/useUpdateStepFilterFromVariable.ts@@ -0,0 +1,88 @@+import { useGetFieldMetadataItemByIdOrThrow } from '@/object-metadata/hooks/useGetFieldMetadataItemById';+import { useGetInitialFilterValue } from '@/object-record/object-filter-dropdown/hooks/useGetInitialFilterValue';+import { useWorkflowVersionIdOrThrow } from '@/workflow/hooks/useWorkflowVersionIdOrThrow';+import { stepsOutputSchemaFamilySelector } from '@/workflow/states/selectors/stepsOutputSchemaFamilySelector';+import { useUpsertStepFilterSettings } from '@/workflow/workflow-steps/filters/hooks/useUpsertStepFilterSettings';+import { getStepFilterVariableSelectionSettings } from '@/workflow/workflow-steps/filters/utils/getStepFilterVariableSelectionSettings';+import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';+import { searchVariableThroughOutputSchemaV2 } from '@/workflow/workflow-variables/utils/searchVariableThroughOutputSchemaV2';+import { useStore } from 'jotai';+import {+ type FilterableAndTSVectorFieldType,+ type StepFilter,+} from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';+import { extractRawVariableNamePart } from 'twenty-shared/workflow';++export const useUpdateStepFilterFromVariable = ({+ stepFilter,+}: {+ stepFilter: StepFilter;+}) => {+ const { upsertStepFilterSettings } = useUpsertStepFilterSettings();+ const { getFieldMetadataItemByIdOrThrow } =+ useGetFieldMetadataItemByIdOrThrow();+ const workflowVersionId = useWorkflowVersionIdOrThrow();+ const { getInitialFilterValue } = useGetInitialFilterValue();+ const jotaiStore = useStore();++ const updateStepFilterFromVariable = ({+ rawVariableName,+ isFullRecord,+ stepType,+ }: {+ rawVariableName: string;+ isFullRecord: boolean;+ stepType: StepOutputSchemaV2['type'];+ }) => {+ const stepId = extractRawVariableNamePart({+ rawVariableName,+ part: 'stepId',+ });+ const [currentStepOutputSchema] = jotaiStore.get(+ stepsOutputSchemaFamilySelector.selectorFamily({+ workflowVersionId,+ stepIds: [stepId],+ }),+ );++ if (!isDefined(currentStepOutputSchema)) {+ throw new Error(`No output schema found for workflow step ${stepId}`);+ }++ const { variableType, fieldMetadataId, compositeFieldSubFieldName } =+ searchVariableThroughOutputSchemaV2({+ stepOutputSchema: currentStepOutputSchema,+ stepType,+ rawVariableName,+ isFullRecord,+ });+ const { fieldMetadataItem: filterFieldMetadataItem } = isDefined(+ fieldMetadataId,+ )+ ? getFieldMetadataItemByIdOrThrow(fieldMetadataId)+ : { fieldMetadataItem: undefined };+ const variableSelectionSettings = getStepFilterVariableSelectionSettings({+ rawVariableName,+ isFullRecord,+ variableType,+ fieldMetadataId,+ fieldMetadataType: filterFieldMetadataItem?.type,+ compositeFieldSubFieldName,+ });+ const { value } = getInitialFilterValue(+ variableSelectionSettings.type as FilterableAndTSVectorFieldType,+ variableSelectionSettings.operand,+ );++ upsertStepFilterSettings({+ stepFilterToUpsert: {+ ...stepFilter,+ ...variableSelectionSettings,+ value,+ },+ });+ };++ return { updateStepFilterFromVariable };+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/filters/utils/__tests__/getStepFilterVariableSelectionSettings.test.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/filters/utils/__tests__/getStepFilterVariableSelectionSettings.test.tsnew file mode 100644index 00000000000..f6b38724f78--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/filters/utils/__tests__/getStepFilterVariableSelectionSettings.test.ts@@ -0,0 +1,97 @@+import { getStepFilterVariableSelectionSettings } from '@/workflow/workflow-steps/filters/utils/getStepFilterVariableSelectionSettings';+import { FieldMetadataType, ViewFilterOperand } from 'twenty-shared/types';++describe('getStepFilterVariableSelectionSettings', () => {+ it('uses the variable type and resets to its default operand', () => {+ expect(+ getStepFilterVariableSelectionSettings({+ rawVariableName: '{{find.totalCount}}',+ isFullRecord: false,+ variableType: 'number',+ fieldMetadataId: undefined,+ fieldMetadataType: undefined,+ compositeFieldSubFieldName: undefined,+ }),+ ).toEqual({+ stepOutputKey: '{{find.totalCount}}',+ isFullRecord: false,+ type: 'number',+ fieldMetadataId: undefined,+ compositeFieldSubFieldName: undefined,+ operand: ViewFilterOperand.IS,+ });+ });++ it('uses field metadata and composite subfield behavior', () => {+ expect(+ getStepFilterVariableSelectionSettings({+ rawVariableName: '{{trigger.amount.currencyCode}}',+ isFullRecord: false,+ variableType: 'string',+ fieldMetadataId: 'amount',+ fieldMetadataType: FieldMetadataType.CURRENCY,+ compositeFieldSubFieldName: 'currencyCode',+ }),+ ).toEqual({+ stepOutputKey: '{{trigger.amount.currencyCode}}',+ isFullRecord: false,+ type: FieldMetadataType.CURRENCY,+ fieldMetadataId: 'amount',+ compositeFieldSubFieldName: 'currencyCode',+ operand: ViewFilterOperand.IS,+ });+ });++ it('normalizes morph relations to relation filters', () => {+ expect(+ getStepFilterVariableSelectionSettings({+ rawVariableName: '{{trigger.people.id}}',+ isFullRecord: false,+ variableType: 'string',+ fieldMetadataId: 'people',+ fieldMetadataType: FieldMetadataType.MORPH_RELATION,+ compositeFieldSubFieldName: undefined,+ }),+ ).toEqual(+ expect.objectContaining({+ type: FieldMetadataType.RELATION,+ operand: ViewFilterOperand.IS,+ }),+ );+ });++ it('keeps field types without a specialized filter mapping', () => {+ expect(+ getStepFilterVariableSelectionSettings({+ rawVariableName: '{{trigger.description}}',+ isFullRecord: false,+ variableType: 'string',+ fieldMetadataId: 'description',+ fieldMetadataType: FieldMetadataType.RICH_TEXT,+ compositeFieldSubFieldName: undefined,+ }),+ ).toEqual(+ expect.objectContaining({+ type: FieldMetadataType.RICH_TEXT,+ }),+ );+ });++ it('retains whole-record selection', () => {+ expect(+ getStepFilterVariableSelectionSettings({+ rawVariableName: '{{find.first.id}}',+ isFullRecord: true,+ variableType: 'string',+ fieldMetadataId: undefined,+ fieldMetadataType: undefined,+ compositeFieldSubFieldName: undefined,+ }),+ ).toEqual(+ expect.objectContaining({+ stepOutputKey: '{{find.first.id}}',+ isFullRecord: true,+ }),+ );+ });+});diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/filters/utils/getStepFilterVariableSelectionSettings.ts b/packages/twenty-front/src/modules/workflow/workflow-steps/filters/utils/getStepFilterVariableSelectionSettings.tsnew file mode 100644index 00000000000..0f6b07b0069--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/filters/utils/getStepFilterVariableSelectionSettings.ts@@ -0,0 +1,57 @@+import { getStepFilterOperands } from '@/workflow/workflow-steps/filters/utils/getStepFilterOperands';+import { FieldMetadataType, type StepFilter } from 'twenty-shared/types';+import { isDefined } from 'twenty-shared/utils';++type StepFilterVariableSelectionSettings = Pick<+ StepFilter,+ | 'stepOutputKey'+ | 'isFullRecord'+ | 'type'+ | 'fieldMetadataId'+ | 'compositeFieldSubFieldName'+ | 'operand'+>;++export const getStepFilterVariableSelectionSettings = ({+ rawVariableName,+ isFullRecord,+ variableType,+ fieldMetadataId,+ fieldMetadataType,+ compositeFieldSubFieldName,+}: {+ rawVariableName: string;+ isFullRecord: boolean;+ variableType: string | undefined;+ fieldMetadataId: string | undefined;+ fieldMetadataType: FieldMetadataType | undefined;+ compositeFieldSubFieldName: string | undefined;+}): StepFilterVariableSelectionSettings => {+ const filterType = (() => {+ if (!isDefined(fieldMetadataId)) {+ return variableType ?? 'unknown';+ }++ if (isDefined(fieldMetadataType)) {+ return fieldMetadataType === FieldMetadataType.MORPH_RELATION+ ? FieldMetadataType.RELATION+ : fieldMetadataType;+ }++ return 'unknown';+ })();++ const [defaultOperand] = getStepFilterOperands({+ filterType,+ subFieldName: compositeFieldSubFieldName,+ });++ return {+ stepOutputKey: rawVariableName,+ isFullRecord,+ type: filterType,+ fieldMetadataId,+ compositeFieldSubFieldName,+ operand: defaultOperand,+ };+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariableSearchResultItems.tsx b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariableSearchResultItems.tsxnew file mode 100644index 00000000000..48128a61881--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariableSearchResultItems.tsx@@ -0,0 +1,34 @@+import { type WorkflowVariableSearchResult } from '@/workflow/workflow-variables/types/WorkflowVariableSearchResult';+import { useIcons } from 'twenty-ui/icon';+import { MenuItemSelect } from 'twenty-ui/navigation';++type WorkflowVariableSearchResultItemsProps = {+ searchResults: WorkflowVariableSearchResult[];+ onSelect: (result: WorkflowVariableSearchResult) => void;+};++export const WorkflowVariableSearchResultItems = ({+ searchResults,+ onSelect,+}: WorkflowVariableSearchResultItemsProps) => {+ const { getIcon } = useIcons();++ return searchResults.map((result) => (+ <MenuItemSelect+ key={JSON.stringify([+ result.stepId,+ result.path,+ result.isLeaf,+ result.isFullRecord,+ ])}+ selected={false}+ focused={false}+ onClick={() => onSelect(result)}+ text={result.label}+ contextualText={result.breadcrumb}+ LeftIcon={getIcon(result.icon)}+ leftIconColor={result.iconColor}+ hasSubMenu={!result.isLeaf}+ />+ ));+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdown.tsx b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdown.tsxindex 42a17a8cc01..32e3e5d8352 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdown.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdown.tsx@@ -7,6 +7,7 @@ import { type InputSchemaPropertyType } from 'twenty-shared/workflow';import { useAvailableVariablesInWorkflowStep } from '@/workflow/workflow-variables/hooks/useAvailableVariablesInWorkflowStep';import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';+import { type WorkflowVariableStepSelection } from '@/workflow/workflow-variables/types/WorkflowVariableSelection';import { t } from '@lingui/core/macro';import { styled } from '@linaria/react';import { useContext, useState } from 'react';@@ -68,8 +69,13 @@ export const WorkflowVariablesDropdown = ({const [selectedStep, setSelectedStep] = useState<StepOutputSchemaV2 | undefined>(initialStep);+ const [selectedPath, setSelectedPath] = useState<string[]>([]);- const handleStepSelect = (stepId: string) => {+ const handleStepSelect = ({+ stepId,+ path = [],+ }: WorkflowVariableStepSelection) => {+ setSelectedPath(path);setSelectedStep(availableVariablesInWorkflowStep.find((step) => step.id === stepId),);@@ -78,6 +84,7 @@ export const WorkflowVariablesDropdown = ({const handleSubItemSelect = (subItem: string) => {onVariableSelect(subItem);setSelectedStep(initialStep);+ setSelectedPath([]);closeDropdown(dropdownId);};@@ -126,10 +133,16 @@ export const WorkflowVariablesDropdown = ({dropdownId={dropdownId}steps={availableVariablesInWorkflowStep}onSelect={handleStepSelect}+ onVariableSelect={({ rawVariableName }) =>+ handleSubItemSelect(rawVariableName)+ }+ shouldDisplayRecordObjects={shouldDisplayRecordObjects}+ objectNameSingularsToSelect={objectNameSingularsToSelect}/>) : (<WorkflowVariablesDropdownStepItemsstep={selectedStep}+ initialPath={selectedPath}onSelect={handleSubItemSelect}onBack={handleBack}shouldDisplayRecordObjects={shouldDisplayRecordObjects}diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdownStepItems.tsx b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdownStepItems.tsxindex e4e6e1552a1..951c372e351 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdownStepItems.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdownStepItems.tsx@@ -4,10 +4,10 @@ import { DropdownMenuSearchInput } from '@/ui/layout/dropdown/components/Dropdowimport { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';-import { useObjectMetadataSelectHelpers } from '@/object-metadata/hooks/useObjectMetadataSelectHelpers';import { DropdownContent } from '@/ui/layout/dropdown/components/DropdownContent';import { DropdownMenuHeaderLeftComponent } from '@/ui/layout/dropdown/components/DropdownMenuHeader/internal/DropdownMenuHeaderLeftComponent';import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';+import { WorkflowVariableSearchResultItems } from '@/workflow/workflow-variables/components/WorkflowVariableSearchResultItems';import { useVariableDropdown } from '@/workflow/workflow-variables/hooks/useVariableDropdown';import { isRecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2';import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';@@ -15,6 +15,7 @@ import { getCurrentSubStepFromPath } from '@/workflow/workflow-variables/utils/gimport { getStepHeaderLabel } from '@/workflow/workflow-variables/utils/getStepHeaderLabel';import { getStepItemIcon } from '@/workflow/workflow-variables/utils/getStepItemIcon';import { getVariableTemplateFromPath } from '@/workflow/workflow-variables/utils/getVariableTemplateFromPath';+import { getWorkflowVariableRecordObjectDisplay } from '@/workflow/workflow-variables/utils/getWorkflowVariableRecordObjectDisplay';import {getWorkflowVariableSpecialItems,type WorkflowVariableSpecialItem,@@ -27,6 +28,7 @@ import { OverflowingTextWithTooltip } from 'twenty-ui/surfaces';type WorkflowVariablesDropdownStepItemsProps = {step: StepOutputSchemaV2;+ initialPath?: string[];onSelect: (value: string) => void;onBack: () => void;shouldDisplayRecordObjects: boolean;@@ -35,6 +37,7 @@ type WorkflowVariablesDropdownStepItemsProps = {export const WorkflowVariablesDropdownStepItems = ({step,+ initialPath,onSelect,onBack,shouldDisplayRecordObjects,@@ -42,19 +45,23 @@ export const WorkflowVariablesDropdownStepItems = ({}: WorkflowVariablesDropdownStepItemsProps) => {const { t } = useLingui();const { getIcon } = useIcons();- const { getSelectIconPropsFromObjectMetadataItem } =- useObjectMetadataSelectHelpers();const {searchInputValue,setSearchInputValue,handleSelectField,goBack,- filteredOptions,+ options,currentPath,+ isSearching,+ searchResults,+ handleSelectSearchResult,} = useVariableDropdown({step,- onSelect,+ initialPath,+ onSelect: ({ rawVariableName }) => onSelect(rawVariableName),onBack,+ shouldDisplayRecordObjects,+ objectNameSingularsToSelect,});const { objectMetadataItems } = useObjectMetadataItems();@@ -87,7 +94,6 @@ export const WorkflowVariablesDropdownStepItems = ({const specialItems = getWorkflowVariableSpecialItems({step,currentPath,- searchInputValue,});const handleSelectSpecialItem = (@@ -109,32 +115,17 @@ export const WorkflowVariablesDropdownStepItems = ({): undefined;- const isObjectFoundThroughSearch = isDefined(searchInputValue)- ? isDefined(displayedSubStepObject?.label) &&- displayedSubStepObject?.label- .toLowerCase()- .includes(searchInputValue.toLowerCase())- : true;-- const objectLabel = displayedSubStepObjectMetadata?.labelSingular;-- const isSubStepObjectSelectable =- !isDefined(objectNameSingularsToSelect) ||- (isDefined(displayedSubStepObjectMetadata) &&- objectNameSingularsToSelect.includes(- displayedSubStepObjectMetadata.nameSingular,- ));+ const displayedSubStepObjectDisplay = isDefined(displayedSubStepObject)+ ? getWorkflowVariableRecordObjectDisplay({+ recordObject: displayedSubStepObject,+ objectMetadataItem: displayedSubStepObjectMetadata,+ objectNameSingularsToSelect,+ })+ : undefined;const shouldDisplaySubStepObject =shouldDisplayRecordObjects &&- isObjectFoundThroughSearch &&- isSubStepObjectSelectable;-- const displayedSubStepObjectIconProps = isDefined(- displayedSubStepObjectMetadata,- )- ? getSelectIconPropsFromObjectMetadataItem(displayedSubStepObjectMetadata)- : undefined;+ displayedSubStepObjectDisplay?.isSelectable === true;return (<DropdownContent widthInPixels={GenericDropdownContentWidth.ExtraLarge}>@@ -157,62 +148,71 @@ export const WorkflowVariablesDropdownStepItems = ({/><DropdownMenuSeparator /><DropdownMenuItemsContainer hasMaxHeight>- {specialItems.map((specialItem) => (- <MenuItemSelect- key={specialItem.id}- selected={false}- focused={false}- onClick={() => handleSelectSpecialItem(specialItem)}- text={specialItem.label}- hasSubMenu={false}- LeftIcon={getIcon(specialItem.iconName)}- contextualText={specialItem.contextualText}+ {isSearching ? (+ <WorkflowVariableSearchResultItems+ searchResults={searchResults}+ onSelect={handleSelectSearchResult}/>- ))}- {shouldDisplaySubStepObject && (- <MenuItemSelect- selected={false}- focused={false}- onClick={handleSelectObject}- text={objectLabel || ''}- hasSubMenu={false}- LeftIcon={displayedSubStepObjectIconProps?.Icon}- leftIconColor={displayedSubStepObjectIconProps?.iconThemeColor}- contextualText={t`Pick a ${objectLabel} record`}- />- )}- {filteredOptions.length > 0 &&- (shouldDisplaySubStepObject || specialItems.length > 0) && (- <DropdownMenuSeparator />- )}- {filteredOptions.map(([key, subStep]) => {- if (!isDefined(subStep)) {- return null;- }-- return (- <MenuItemSelect- key={key}- selected={false}- focused={false}- onClick={() => handleSelectField(key)}- text={subStep.label || key}- hasSubMenu={!subStep.isLeaf}- LeftIcon={- subStep.icon- ? getIcon(subStep.icon)- : getIcon(- getStepItemIcon({- itemType: subStep.type,- }),- )- }- contextualText={- subStep.isLeaf ? subStep?.value?.toString() : undefined+ ) : (+ <>+ {specialItems.map((specialItem) => (+ <MenuItemSelect+ key={specialItem.id}+ selected={false}+ focused={false}+ onClick={() => handleSelectSpecialItem(specialItem)}+ text={specialItem.label}+ hasSubMenu={false}+ LeftIcon={getIcon(specialItem.iconName)}+ contextualText={specialItem.contextualText}+ />+ ))}+ {shouldDisplaySubStepObject && (+ <MenuItemSelect+ selected={false}+ focused={false}+ onClick={handleSelectObject}+ text={displayedSubStepObjectDisplay?.label ?? ''}+ hasSubMenu={false}+ LeftIcon={getIcon(displayedSubStepObjectDisplay?.icon)}+ leftIconColor={displayedSubStepObjectDisplay?.iconColor}+ contextualText={t`Pick a ${displayedSubStepObjectDisplay?.label} record`}+ />+ )}+ {options.length > 0 &&+ (shouldDisplaySubStepObject || specialItems.length > 0) && (+ <DropdownMenuSeparator />+ )}+ {options.map(([key, subStep]) => {+ if (!isDefined(subStep)) {+ return null;}- />- );- })}++ return (+ <MenuItemSelect+ key={key}+ selected={false}+ focused={false}+ onClick={() => handleSelectField(key)}+ text={subStep.label || key}+ hasSubMenu={!subStep.isLeaf}+ LeftIcon={+ subStep.icon+ ? getIcon(subStep.icon)+ : getIcon(+ getStepItemIcon({+ itemType: subStep.type,+ }),+ )+ }+ contextualText={+ subStep.isLeaf ? subStep.value?.toString() : undefined+ }+ />+ );+ })}+ </>+ )}</DropdownMenuItemsContainer></DropdownContent>);diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdownSteps.tsx b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdownSteps.tsxindex 12a3bb95b77..1082bdc23ce 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdownSteps.tsx+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/components/WorkflowVariablesDropdownSteps.tsx@@ -5,8 +5,17 @@ import { DropdownMenuItemsContainer } from '@/ui/layout/dropdown/components/Dropimport { DropdownMenuSearchInput } from '@/ui/layout/dropdown/components/DropdownMenuSearchInput';import { DropdownMenuSeparator } from '@/ui/layout/dropdown/components/DropdownMenuSeparator';import { GenericDropdownContentWidth } from '@/ui/layout/dropdown/constants/GenericDropdownContentWidth';+import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';+import { WorkflowVariableSearchResultItems } from '@/workflow/workflow-variables/components/WorkflowVariableSearchResultItems';import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';+import { type WorkflowVariableSearchResult } from '@/workflow/workflow-variables/types/WorkflowVariableSearchResult';+import {+ type WorkflowVariableSelection,+ type WorkflowVariableStepSelection,+} from '@/workflow/workflow-variables/types/WorkflowVariableSelection';+import { getWorkflowVariableSelectionFromSearchResult } from '@/workflow/workflow-variables/utils/getWorkflowVariableSelectionFromSearchResult';+import { searchWorkflowVariables } from '@/workflow/workflow-variables/utils/searchWorkflowVariables';import { t } from '@lingui/core/macro';import { useState } from 'react';import { IconX, useIcons } from 'twenty-ui/icon';@@ -16,24 +25,49 @@ import { MenuItem, MenuItemSelect } from 'twenty-ui/navigation';type WorkflowVariablesDropdownStepsProps = {dropdownId: string;steps: StepOutputSchemaV2[];- onSelect: (value: string) => void;+ onSelect: (selection: WorkflowVariableStepSelection) => void;+ onVariableSelect: (selection: WorkflowVariableSelection) => void;+ shouldDisplaySpecialItems?: boolean;+ shouldDisplayRecordObjects?: boolean;+ objectNameSingularsToSelect?: string[];};export const WorkflowVariablesDropdownSteps = ({dropdownId,steps,onSelect,+ onVariableSelect,+ shouldDisplaySpecialItems,+ shouldDisplayRecordObjects,+ objectNameSingularsToSelect,}: WorkflowVariablesDropdownStepsProps) => {const { getIcon } = useIcons();+ const { objectMetadataItems } = useObjectMetadataItems();const [searchInputValue, setSearchInputValue] = useState('');const { closeDropdown } = useCloseDropdown();+ const search = searchInputValue.trim().toLowerCase();const availableSteps = steps.filter((step) =>- searchInputValue- ? step.name.toLowerCase().includes(searchInputValue)- : true,+ step.name.toLowerCase().includes(search),);+ const matchingVariables = searchWorkflowVariables({+ steps,+ searchInputValue,+ shouldDisplaySpecialItems,+ shouldDisplayRecordObjects,+ objectNameSingularsToSelect,+ objectMetadataItems,+ });++ const handleSearchResultSelect = (variable: WorkflowVariableSearchResult) => {+ if (!variable.isLeaf) {+ onSelect({ stepId: variable.stepId, path: variable.path });+ return;+ }++ onVariableSelect(getWorkflowVariableSelectionFromSearchResult(variable));+ };return (<DropdownContent widthInPixels={GenericDropdownContentWidth.ExtraLarge}>@@ -49,24 +83,31 @@ export const WorkflowVariablesDropdownSteps = ({</DropdownMenuHeader><DropdownMenuSearchInputautoFocus+ placeholder={t`Search steps and fields`}value={searchInputValue}onChange={(event) => setSearchInputValue(event.target.value)}/><DropdownMenuSeparator /><DropdownMenuItemsContainer hasMaxHeight>- {availableSteps.length > 0 ? (- availableSteps.map((item, _index) => (- <MenuItemSelect- key={`step-${item.id}`}- selected={false}- focused={false}- onClick={() => onSelect(item.id)}- text={item.name}- LeftIcon={item.icon ? getIcon(item.icon) : undefined}- hasSubMenu- />- ))- ) : (+ <WorkflowVariableSearchResultItems+ searchResults={matchingVariables}+ onSelect={handleSearchResultSelect}+ />+ {matchingVariables.length > 0 && availableSteps.length > 0 && (+ <DropdownMenuSeparator />+ )}+ {availableSteps.map((item) => (+ <MenuItemSelect+ key={`step-${item.id}`}+ selected={false}+ focused={false}+ onClick={() => onSelect({ stepId: item.id })}+ text={item.name}+ LeftIcon={item.icon ? getIcon(item.icon) : undefined}+ hasSubMenu+ />+ ))}+ {matchingVariables.length === 0 && availableSteps.length === 0 && (<MenuItemkey="no-steps"onClick={() => {}}diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/components/__stories__/WorkflowVariablesDropdownStepItems.stories.tsx b/packages/twenty-front/src/modules/workflow/workflow-variables/components/__stories__/WorkflowVariablesDropdownStepItems.stories.tsxnew file mode 100644index 00000000000..0c9607dbddf--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/components/__stories__/WorkflowVariablesDropdownStepItems.stories.tsx@@ -0,0 +1,63 @@+import { WorkflowVariablesDropdownStepItems } from '@/workflow/workflow-variables/components/WorkflowVariablesDropdownStepItems';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, fn, userEvent, within } from 'storybook/test';+import { ComponentDecorator } from 'twenty-ui/testing';+import { WorkflowStepDecorator } from '~/testing/decorators/WorkflowStepDecorator';+import { WorkspaceDecorator } from '~/testing/decorators/WorkspaceDecorator';++const ASYNC_DECORATOR_WAIT_OPTIONS = { timeout: 5_000 };++const meta = {+ title: 'Modules/Workflow/Variables/WorkflowVariablesDropdownStepItems',+ component: WorkflowVariablesDropdownStepItems,+ args: {+ step: {+ id: 'code',+ name: 'Run code',+ type: 'CODE',+ outputSchema: {+ result: {+ isLeaf: false,+ type: 'object',+ label: 'Result',+ value: {+ employees: {+ isLeaf: true,+ label: 'Employees',+ type: 'number',+ value: 5,+ },+ },+ },+ },+ },+ onSelect: fn(),+ onBack: fn(),+ shouldDisplayRecordObjects: false,+ },+ decorators: [WorkflowStepDecorator, ComponentDecorator, WorkspaceDecorator],+} satisfies Meta<typeof WorkflowVariablesDropdownStepItems>;++export default meta;+type Story = StoryObj<typeof meta>;++export const NestedFieldSearch: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ const searchInput = await canvas.findByRole(+ 'textbox',+ undefined,+ ASYNC_DECORATOR_WAIT_OPTIONS,+ );++ expect(canvas.getByText('Result')).toBeInTheDocument();+ expect(canvas.queryByText('Employees')).not.toBeInTheDocument();+ await userEvent.type(searchInput, ' EMPLOYEES ');+ expect(+ canvas.getByText('Run code / Result', { exact: false }),+ ).toBeInTheDocument();+ await userEvent.click(canvas.getByText('Employees'));+ expect(args.onSelect).toHaveBeenCalledWith('{{code.result.employees}}');+ },+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/components/__stories__/WorkflowVariablesDropdownSteps.stories.tsx b/packages/twenty-front/src/modules/workflow/workflow-variables/components/__stories__/WorkflowVariablesDropdownSteps.stories.tsxnew file mode 100644index 00000000000..10229e45b7b--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/components/__stories__/WorkflowVariablesDropdownSteps.stories.tsx@@ -0,0 +1,183 @@+import { WorkflowVariablesDropdownSteps } from '@/workflow/workflow-variables/components/WorkflowVariablesDropdownSteps';+import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';+import { type Meta, type StoryObj } from '@storybook/react-vite';+import { expect, fn, userEvent, within } from 'storybook/test';+import { ComponentDecorator } from 'twenty-ui/testing';+import { ObjectMetadataItemsDecorator } from '~/testing/decorators/ObjectMetadataItemsDecorator';+import { WorkspaceDecorator } from '~/testing/decorators/WorkspaceDecorator';+import { graphqlMocks } from '~/testing/graphqlMocks';++const STEPS: StepOutputSchemaV2[] = [+ {+ id: 'trigger',+ name: 'Manual trigger',+ type: 'MANUAL',+ outputSchema: {+ companyName: {+ isLeaf: true,+ label: 'Company name',+ type: 'string',+ value: '',+ },+ },+ },+ {+ id: 'code',+ name: 'Run code',+ type: 'CODE',+ outputSchema: {+ result: {+ isLeaf: false,+ type: 'object',+ label: 'Result',+ value: {+ companyName: {+ isLeaf: true,+ label: 'Company name',+ type: 'string',+ value: '',+ },+ },+ },+ },+ },+];++const ASYNC_DECORATOR_WAIT_OPTIONS = { timeout: 5_000 };++const meta = {+ title: 'Modules/Workflow/Variables/WorkflowVariablesDropdownSteps',+ component: WorkflowVariablesDropdownSteps,+ parameters: {+ msw: graphqlMocks,+ },+ args: {+ dropdownId: 'variables',+ steps: STEPS,+ onSelect: fn(),+ onVariableSelect: fn(),+ },+ decorators: [+ ComponentDecorator,+ ObjectMetadataItemsDecorator,+ WorkspaceDecorator,+ ],+} satisfies Meta<typeof WorkflowVariablesDropdownSteps>;++export default meta;+type Story = StoryObj<typeof meta>;++export const Default: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ const runCodeItem = await canvas.findByText(+ 'Run code',+ undefined,+ ASYNC_DECORATOR_WAIT_OPTIONS,+ );++ expect(canvas.queryByText('Company name')).not.toBeInTheDocument();+ await userEvent.click(runCodeItem);+ expect(args.onSelect).toHaveBeenCalledWith({ stepId: 'code' });+ },+};++export const NestedFieldSearch: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ const searchInput = await canvas.findByPlaceholderText(+ 'Search steps and fields',+ undefined,+ ASYNC_DECORATOR_WAIT_OPTIONS,+ );++ await userEvent.type(searchInput, ' COMPANY NAME ');+ expect(canvas.getAllByText('Company name')).toHaveLength(2);+ expect(+ canvas.getByText('Run code / Result', { exact: false }),+ ).toBeInTheDocument();+ await userEvent.click(canvas.getAllByText('Company name')[1]);+ expect(args.onVariableSelect).toHaveBeenCalledWith({+ rawVariableName: '{{code.result.companyName}}',+ stepId: 'code',+ isFullRecord: false,+ });+ expect(args.onSelect).not.toHaveBeenCalled();+ },+};++export const NestedContainerSearch: Story = {+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ const searchInput = await canvas.findByPlaceholderText(+ 'Search steps and fields',+ undefined,+ ASYNC_DECORATOR_WAIT_OPTIONS,+ );++ await userEvent.type(searchInput, 'result');+ await userEvent.click(canvas.getByText('Result'));+ expect(args.onSelect).toHaveBeenCalledWith({+ stepId: 'code',+ path: ['result'],+ });+ expect(args.onVariableSelect).not.toHaveBeenCalled();+ },+};++export const WholeRecordSearch: Story = {+ args: {+ shouldDisplayRecordObjects: true,+ steps: [+ {+ id: 'trigger',+ name: 'Record created',+ type: 'DATABASE_EVENT',+ outputSchema: {+ _outputSchemaType: 'RECORD',+ object: { label: 'Company', objectMetadataId: 'company' },+ fields: {},+ },+ },+ ],+ },+ play: async ({ canvasElement, args }) => {+ const canvas = within(canvasElement);++ const searchInput = await canvas.findByPlaceholderText(+ 'Search steps and fields',+ undefined,+ ASYNC_DECORATOR_WAIT_OPTIONS,+ );++ await userEvent.type(searchInput, 'company');+ await userEvent.click(canvas.getByText('Company'));+ expect(args.onVariableSelect).toHaveBeenCalledWith({+ rawVariableName: '{{trigger.id}}',+ stepId: 'trigger',+ isFullRecord: true,+ });+ },+};++export const StepSearchAndEmptyState: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const searchInput = await canvas.findByPlaceholderText(+ 'Search steps and fields',+ undefined,+ ASYNC_DECORATOR_WAIT_OPTIONS,+ );++ await userEvent.type(searchInput, 'RUN CODE');+ expect(canvas.getByText('Run code')).toBeInTheDocument();+ expect(canvas.queryByText('Manual trigger')).not.toBeInTheDocument();+ await userEvent.clear(searchInput);+ expect(canvas.getByText('Manual trigger')).toBeInTheDocument();+ await userEvent.type(searchInput, 'unavailable');+ expect(canvas.getByText('No variables available')).toBeInTheDocument();+ },+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/hooks/useVariableDropdown.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/hooks/useVariableDropdown.tsindex d9b05a99a68..7265ace94a9 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/hooks/useVariableDropdown.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/hooks/useVariableDropdown.ts@@ -1,3 +1,4 @@+import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';import { useSidePanelWorkflowNavigation } from '@/side-panel/pages/workflow/hooks/useSidePanelWorkflowNavigation';import { sidePanelNavigationStackState } from '@/side-panel/states/sidePanelNavigationStackState';import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';@@ -9,21 +10,40 @@ import { workflowSelectedNodeComponentState } from '@/workflow/workflow-diagram/import { type LinkOutputSchema } from '@/workflow/workflow-variables/types/LinkOutputSchema';import { type FieldOutputSchemaV2 } from '@/workflow/workflow-variables/types/RecordOutputSchemaV2';import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';+import { type WorkflowVariableSearchResult } from '@/workflow/workflow-variables/types/WorkflowVariableSearchResult';+import { type WorkflowVariableSelection } from '@/workflow/workflow-variables/types/WorkflowVariableSelection';import { getVariableTemplateFromPath } from '@/workflow/workflow-variables/utils/getVariableTemplateFromPath';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { useState } from 'react';import { isDefined } from 'twenty-shared/utils';-import { type BaseOutputSchemaV2 } from 'twenty-shared/workflow';+import {+ type BaseOutputSchemaV2,+ type InputSchemaPropertyType,+} from 'twenty-shared/workflow';import { useIcons } from 'twenty-ui/icon';import { isBaseOutputSchemaV2 } from '@/workflow/workflow-variables/types/guards/isBaseOutputSchemaV2';import { isLinkOutputSchema } from '@/workflow/workflow-variables/types/guards/isLinkOutputSchema';import { isRecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2';import { getCurrentSubStepFromPath } from '@/workflow/workflow-variables/utils/getCurrentSubStepFromPath';+import { getWorkflowVariableSelectionFromSearchResult } from '@/workflow/workflow-variables/utils/getWorkflowVariableSelectionFromSearchResult';+import { searchWorkflowVariables } from '@/workflow/workflow-variables/utils/searchWorkflowVariables';type UseVariableDropdownProps = {step: StepOutputSchemaV2;- onSelect: (value: string) => void;+ initialPath?: string[];+ onSelect: (selection: WorkflowVariableSelection) => void;onBack: () => void;+ shouldDisplaySpecialItems?: boolean;+ shouldDisplayRecordObjects?: boolean;+ objectNameSingularsToSelect?: string[];+};++type VariableDropdownOption = {+ isLeaf: boolean;+ label?: string;+ icon?: string;+ type?: InputSchemaPropertyType;+ value?: { toString: () => string } | null;};type UseVariableDropdownReturn = {@@ -31,19 +51,26 @@ type UseVariableDropdownReturn = {searchInputValue: string;setSearchInputValue: (value: string) => void;handleSelectField: (key: string) => void;+ isSearching: boolean;+ searchResults: WorkflowVariableSearchResult[];+ handleSelectSearchResult: (result: WorkflowVariableSearchResult) => void;goBack: () => void;- // TODO: fix typing here- filteredOptions: [string, any][];+ options: Array<[string, VariableDropdownOption]>;};export const useVariableDropdown = ({step,+ initialPath = [],onSelect,onBack,+ shouldDisplaySpecialItems,+ shouldDisplayRecordObjects,+ objectNameSingularsToSelect,}: UseVariableDropdownProps): UseVariableDropdownReturn => {const { getIcon } = useIcons();+ const { objectMetadataItems } = useObjectMetadataItems();- const [currentPath, setCurrentPath] = useState<string[]>([]);+ const [currentPath, setCurrentPath] = useState<string[]>(initialPath);const [searchInputValue, setSearchInputValue] = useState('');const { openWorkflowEditStepInSidePanel } = useSidePanelWorkflowNavigation();@@ -90,12 +117,14 @@ export const useVariableDropdown = ({setCurrentPath([...currentPath, key]);setSearchInputValue('');} else {- onSelect(- getVariableTemplateFromPath({+ onSelect({+ rawVariableName: getVariableTemplateFromPath({stepId: step.id,path: [...currentPath, key],}),- );+ stepId: step.id,+ isFullRecord: false,+ });}};@@ -146,6 +175,7 @@ export const useVariableDropdown = ({};const goBack = () => {+ setSearchInputValue('');if (currentPath.length === 0) {onBack();} else {@@ -156,13 +186,31 @@ export const useVariableDropdown = ({const displayedFields = getDisplayedSubStepFields();const options = displayedFields ? Object.entries(displayedFields) : [];- const filteredOptions = searchInputValue- ? options.filter(- ([_, value]) =>- value.label &&- value.label.toLowerCase().includes(searchInputValue.toLowerCase()),- )- : options;+ const isSearching = searchInputValue.trim().length > 0;+ const searchResults = searchWorkflowVariables({+ steps: [step],+ currentPath,+ searchInputValue,+ shouldDisplaySpecialItems,+ shouldDisplayRecordObjects,+ objectNameSingularsToSelect,+ objectMetadataItems,+ });++ const handleSelectSearchResult = (result: WorkflowVariableSearchResult) => {+ if (result.isLeaf) {+ onSelect(getWorkflowVariableSelectionFromSearchResult(result));+ return;+ }++ if (isLinkOutputSchema(getCurrentSubStepFromPath(step, currentPath))) {+ handleSelectField('link');+ return;+ }++ setCurrentPath(result.path);+ setSearchInputValue('');+ };return {currentPath,@@ -170,6 +218,9 @@ export const useVariableDropdown = ({setSearchInputValue,handleSelectField,goBack,- filteredOptions,+ options,+ isSearching,+ searchResults,+ handleSelectSearchResult,};};diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/types/WorkflowVariableSearchResult.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/types/WorkflowVariableSearchResult.tsnew file mode 100644index 00000000000..5fcefbe24be--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/types/WorkflowVariableSearchResult.ts@@ -0,0 +1,12 @@+import { type ThemeColor } from 'twenty-ui/theme';++export type WorkflowVariableSearchResult = {+ stepId: string;+ path: string[];+ label: string;+ breadcrumb: string;+ icon?: string;+ iconColor?: ThemeColor;+ isLeaf: boolean;+ isFullRecord?: boolean;+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/types/WorkflowVariableSelection.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/types/WorkflowVariableSelection.tsnew file mode 100644index 00000000000..3c5608e3f47--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/types/WorkflowVariableSelection.ts@@ -0,0 +1,10 @@+export type WorkflowVariableStepSelection = {+ stepId: string;+ path?: string[];+};++export type WorkflowVariableSelection = {+ rawVariableName: string;+ stepId: string;+ isFullRecord: boolean;+};diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2.tsindex 22f90fe1cdb..8761e29d07d 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2.ts@@ -1,9 +1,8 @@import { type RecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/RecordOutputSchemaV2';-import { type OutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';import { isObject } from '@sniptt/guards';export const isRecordOutputSchemaV2 = (- outputSchema: OutputSchemaV2,+ outputSchema: unknown,): outputSchema is RecordOutputSchemaV2 => {return (isObject(outputSchema) &&diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/filterOutputSchema.test.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/filterOutputSchema.test.tsindex 04542829df8..7fa52642680 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/filterOutputSchema.test.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/filterOutputSchema.test.ts@@ -1,4 +1,5 @@import { type RecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/RecordOutputSchemaV2';+import { type FindRecordsOutputSchema } from '@/workflow/workflow-variables/types/FindRecordsOutputSchema';import { FieldMetadataType } from 'twenty-shared/types';import { type BaseOutputSchemaV2 } from 'twenty-shared/workflow';import { filterOutputSchema } from '@/workflow/workflow-variables/utils/filterOutputSchema';@@ -265,5 +266,118 @@ describe('filterOutputSchema', () => {}),).toEqual(inputSchema);});++ it('should filter out excluded types from nested schemas', () => {+ const inputSchema = createRecordSchema('person', {+ company: {+ isLeaf: false,+ type: FieldMetadataType.RELATION,+ value: createRecordSchema('company', {+ name: { isLeaf: true, type: FieldMetadataType.TEXT },+ score: { isLeaf: true, type: FieldMetadataType.RATING },+ }),+ },+ });++ expect(+ filterOutputSchema({+ shouldDisplayRecordFields: true,+ shouldDisplayRecordObjects: true,+ outputSchema: inputSchema,+ fieldTypesToExclude: [FieldMetadataType.RATING],+ }),+ ).toEqual(+ createRecordSchema('person', {+ company: {+ isLeaf: false,+ type: FieldMetadataType.RELATION,+ value: createRecordSchema('company', {+ name: { isLeaf: true, type: FieldMetadataType.TEXT },+ }),+ },+ }),+ );+ });++ it('should filter out excluded types from nested non-record fields', () => {+ const inputSchema = createRecordSchema('person', {+ details: {+ isLeaf: false,+ type: 'object',+ value: {+ metrics: {+ isLeaf: false,+ type: 'object',+ value: {+ label: { isLeaf: true, type: FieldMetadataType.TEXT },+ score: { isLeaf: true, type: FieldMetadataType.RATING },+ },+ },+ },+ },+ });++ expect(+ filterOutputSchema({+ shouldDisplayRecordFields: true,+ shouldDisplayRecordObjects: true,+ outputSchema: inputSchema,+ fieldTypesToExclude: [FieldMetadataType.RATING],+ }),+ ).toEqual(+ createRecordSchema('person', {+ details: {+ isLeaf: false,+ type: 'object',+ value: {+ metrics: {+ isLeaf: false,+ type: 'object',+ value: {+ label: { isLeaf: true, type: FieldMetadataType.TEXT },+ },+ },+ },+ },+ }),+ );+ });++ it('should preserve step outputs while filtering their nested records', () => {+ const inputSchema: FindRecordsOutputSchema = {+ first: {+ isLeaf: false,+ label: 'First company',+ value: createRecordSchema('company', {+ name: { isLeaf: true, type: FieldMetadataType.TEXT },+ score: { isLeaf: true, type: FieldMetadataType.RATING },+ }),+ },+ all: undefined,+ totalCount: {+ isLeaf: true,+ type: 'number',+ label: 'Total count',+ value: 1,+ },+ };++ expect(+ filterOutputSchema({+ shouldDisplayRecordFields: true,+ shouldDisplayRecordObjects: true,+ outputSchema: inputSchema,+ fieldTypesToExclude: [FieldMetadataType.RATING],+ }),+ ).toEqual({+ ...inputSchema,+ first: {+ ...inputSchema.first,+ value: createRecordSchema('company', {+ name: { isLeaf: true, type: FieldMetadataType.TEXT },+ }),+ },+ });+ });});});diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/searchWorkflowVariables.test.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/searchWorkflowVariables.test.tsnew file mode 100644index 00000000000..9d61cfde6f5--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/__tests__/searchWorkflowVariables.test.ts@@ -0,0 +1,345 @@+import { type RecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/RecordOutputSchemaV2';+import { type StepOutputSchemaV2 } from '@/workflow/workflow-variables/types/StepOutputSchemaV2';+import { filterOutputSchema } from '@/workflow/workflow-variables/utils/filterOutputSchema';+import { getVariableTemplateFromPath } from '@/workflow/workflow-variables/utils/getVariableTemplateFromPath';+import { searchWorkflowVariables } from '@/workflow/workflow-variables/utils/searchWorkflowVariables';+import { FieldMetadataType } from 'twenty-shared/types';++const COMPANY_SCHEMA: RecordOutputSchemaV2 = {+ _outputSchemaType: 'RECORD',+ object: { label: 'Company', objectMetadataId: 'company' },+ fields: {+ name: {+ isLeaf: true,+ label: 'Company name',+ type: FieldMetadataType.TEXT,+ value: 'Acme',+ fieldMetadataId: 'name',+ isCompositeSubField: false,+ },+ employees: {+ isLeaf: true,+ label: 'Employees',+ type: FieldMetadataType.NUMBER,+ value: 10,+ fieldMetadataId: 'employees',+ isCompositeSubField: false,+ },+ },+};++const STEPS: StepOutputSchemaV2[] = [+ {+ id: 'trigger',+ name: 'Record created',+ type: 'DATABASE_EVENT',+ outputSchema: COMPANY_SCHEMA,+ },+ {+ id: 'find',+ name: 'Find companies',+ type: 'FIND_RECORDS',+ outputSchema: {+ first: { isLeaf: false, label: 'First record', value: COMPANY_SCHEMA },+ all: undefined,+ totalCount: {+ isLeaf: true,+ label: 'Total count',+ type: 'number',+ value: 1,+ },+ },+ },+];++describe('searchWorkflowVariables', () => {+ it('searches only the current subtree while preserving full variable paths', () => {+ const results = searchWorkflowVariables({+ steps: [STEPS[1]],+ currentPath: ['first'],+ searchInputValue: 'company name',+ });++ expect(results).toEqual([+ expect.objectContaining({+ path: ['first', 'name'],+ breadcrumb: 'Find companies / First record',+ }),+ ]);+ expect(+ searchWorkflowVariables({+ steps: [STEPS[1]],+ currentPath: ['first'],+ searchInputValue: 'total count',+ }),+ ).toEqual([]);+ });++ it('finds whole records using their configured identifier field', () => {+ const results = searchWorkflowVariables({+ steps: [+ {+ ...STEPS[0],+ outputSchema: {+ ...COMPANY_SCHEMA,+ object: { ...COMPANY_SCHEMA.object, fieldIdName: 'companyId' },+ fields: {},+ },+ },+ ],+ searchInputValue: ' COMPANY ',+ shouldDisplayRecordObjects: true,+ });++ expect(results).toEqual([+ expect.objectContaining({+ path: ['companyId'],+ label: 'Company',+ isLeaf: true,+ isFullRecord: true,+ }),+ ]);+ });++ it('respects allowed record types without hiding eligible field values', () => {+ const objectMetadataItems = [+ {+ id: 'company',+ nameSingular: 'company',+ labelSingular: 'Business',+ icon: 'IconBuildingSkyscraper',+ color: 'blue',+ isSystem: false,+ },+ ];+ const search = (objectNameSingularsToSelect: string[]) =>+ searchWorkflowVariables({+ steps: STEPS,+ searchInputValue: 'business',+ shouldDisplayRecordObjects: true,+ objectMetadataItems,+ objectNameSingularsToSelect,+ });++ const companyResults = search(['company']);++ expect(companyResults.map((result) => result.path)).toEqual([+ ['id'],+ ['first', 'id'],+ ]);+ expect(companyResults).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ label: 'Business',+ icon: 'IconBuildingSkyscraper',+ iconColor: 'blue',+ }),+ ]),+ );+ expect(search(['person'])).toEqual([]);+ expect(+ searchWorkflowVariables({+ steps: STEPS,+ searchInputValue: 'Business',+ objectMetadataItems,+ }),+ ).toEqual([]);+ expect(+ searchWorkflowVariables({+ steps: STEPS,+ searchInputValue: 'Company name',+ shouldDisplayRecordObjects: true,+ objectMetadataItems,+ objectNameSingularsToSelect: ['person'],+ }),+ ).toHaveLength(2);+ });++ it('finds matching fields across steps and nested records with their source paths', () => {+ const results = searchWorkflowVariables({+ steps: STEPS,+ searchInputValue: ' COMPANY NAME ',+ });++ expect(results).toEqual([+ expect.objectContaining({+ stepId: 'trigger',+ path: ['name'],+ label: 'Company name',+ breadcrumb: 'Record created',+ isLeaf: true,+ }),+ expect.objectContaining({+ stepId: 'find',+ path: ['first', 'name'],+ label: 'Company name',+ breadcrumb: 'Find companies / First record',+ isLeaf: true,+ }),+ ]);+ expect(+ results.map((result) =>+ getVariableTemplateFromPath({+ stepId: result.stepId,+ path: result.path,+ }),+ ),+ ).toEqual(['{{trigger.name}}', '{{find.first.name}}']);+ });++ it.each(['', ' ', 'missing field'])(+ 'returns no field results for %j',+ (searchInputValue) => {+ expect(+ searchWorkflowVariables({ steps: STEPS, searchInputValue }),+ ).toEqual([]);+ },+ );++ it('keeps matching containers navigable rather than treating them as values', () => {+ expect(+ searchWorkflowVariables({ steps: STEPS, searchInputValue: 'first' }),+ ).toEqual([+ expect.objectContaining({+ stepId: 'find',+ path: ['first'],+ isLeaf: false,+ }),+ ]);+ });++ it('uses only the supplied filtered schemas', () => {+ const outputSchema = filterOutputSchema({+ outputSchema: COMPANY_SCHEMA,+ shouldDisplayRecordFields: true,+ shouldDisplayRecordObjects: true,+ fieldTypesToExclude: [FieldMetadataType.TEXT],+ });++ expect(+ searchWorkflowVariables({+ steps: [{ ...STEPS[0], outputSchema: outputSchema ?? {} }],+ searchInputValue: 'Company name',+ }),+ ).toEqual([]);+ expect(+ searchWorkflowVariables({+ steps: [STEPS[1]],+ searchInputValue: 'Company name',+ }).map((result) => result.stepId),+ ).toEqual(['find']);+ });++ it('does not generate variable values for links to configure missing outputs', () => {+ expect(+ searchWorkflowVariables({+ steps: [+ {+ id: 'code',+ name: 'Run code',+ type: 'CODE',+ outputSchema: {+ _outputSchemaType: 'LINK',+ link: { isLeaf: true, label: 'Test code', tab: 'test' },+ },+ },+ ],+ searchInputValue: 'test',+ }),+ ).toEqual([+ expect.objectContaining({+ stepId: 'code',+ path: [],+ label: 'Test code',+ isLeaf: false,+ }),+ ]);+ });++ it('finds whole lists and retains numeric array paths', () => {+ const step: StepOutputSchemaV2 = {+ id: 'code',+ name: 'Run code',+ type: 'CODE',+ outputSchema: {+ '0': { isLeaf: true, type: 'string', label: '0', value: 'Acme' },+ },+ };+ expect(+ searchWorkflowVariables({+ steps: [step],+ searchInputValue: 'whole list',+ }),+ ).toEqual([expect.objectContaining({ path: [], isLeaf: true })]);+ const [result] = searchWorkflowVariables({+ steps: [step],+ searchInputValue: '0',+ });+ expect(+ getVariableTemplateFromPath({ stepId: result.stepId, path: result.path }),+ ).toBe('{{code.0}}');+ expect(+ searchWorkflowVariables({+ steps: [step],+ searchInputValue: 'whole list',+ shouldDisplaySpecialItems: false,+ }),+ ).toEqual([]);+ });++ it('searches iterator records without treating iterator status values as schema nodes', () => {+ const step: StepOutputSchemaV2 = {+ id: 'loop',+ name: 'Loop companies',+ type: 'ITERATOR',+ outputSchema: {+ currentItem: {+ isLeaf: false,+ label: 'Current item',+ value: COMPANY_SCHEMA,+ },+ currentItemIndex: 0,+ hasProcessedAllItems: false,+ },+ };+ expect(+ searchWorkflowVariables({+ steps: [step],+ searchInputValue: 'Company name',+ }),+ ).toEqual([+ expect.objectContaining({ path: ['currentItem', 'name'], isLeaf: true }),+ ]);+ expect(+ searchWorkflowVariables({+ steps: [step],+ searchInputValue: 'Current item',+ }).filter((result) => result.isLeaf),+ ).toEqual([+ expect.objectContaining({ path: ['currentItem'], isLeaf: true }),+ ]);+ });++ it('uses the existing variable path format for field keys', () => {+ const step: StepOutputSchemaV2 = {+ id: 'form',+ name: 'Form',+ type: 'FORM',+ outputSchema: {+ 'company.name': {+ isLeaf: true,+ label: 'Company name',+ type: FieldMetadataType.TEXT,+ value: '',+ },+ },+ };+ const [result] = searchWorkflowVariables({+ steps: [step],+ searchInputValue: 'Company name',+ });+ expect(+ getVariableTemplateFromPath({ stepId: result.stepId, path: result.path }),+ ).toBe('{{form.company.name}}');+ });+});diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/filterOutputSchema.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/filterOutputSchema.tsindex 6d45e8cc878..d2659bc2839 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/filterOutputSchema.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/filterOutputSchema.ts@@ -12,6 +12,7 @@ import { isBaseOutputSchemaV2 } from '@/workflow/workflow-variables/types/guardsimport { isLinkOutputSchema } from '@/workflow/workflow-variables/types/guards/isLinkOutputSchema';import { isRecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2';import { isFieldTypeCompatibleWithRecordId } from '@/workflow/workflow-variables/utils/isFieldTypeCompatibleWithRecordId';+import { isObject } from '@sniptt/guards';import { isDefined } from 'twenty-shared/utils';const isValidRecordOutputSchema = ({@@ -153,16 +154,116 @@ const filterRecordOutputSchemaFieldsByType = ({continue;}- filteredFields[key] = field;+ if (field.isLeaf) {+ filteredFields[key] = field;+ continue;+ }++ const filteredValue = isRecordOutputSchemaV2(field.value)+ ? filterRecordOutputSchemaFieldsByType({+ outputSchema: field.value,+ fieldTypesToExclude,+ })+ : filterNonRecordOutputSchemaFieldsByType({+ outputSchema: field.value,+ fieldTypesToExclude,+ });++ filteredFields[key] = {+ ...field,+ value: filteredValue,+ };}return {...outputSchema,- // Relations could be filtered recursively but this util requires a global simplification firstfields: filteredFields,};};+function filterNonRecordOutputSchemaFieldsByType<+ TOutputSchema extends OutputSchemaV2,+>({+ outputSchema,+ fieldTypesToExclude,+}: {+ outputSchema: TOutputSchema;+ fieldTypesToExclude: InputSchemaPropertyType[];+}): TOutputSchema;+function filterNonRecordOutputSchemaFieldsByType({+ outputSchema,+ fieldTypesToExclude,+}: {+ outputSchema: OutputSchemaV2;+ fieldTypesToExclude: InputSchemaPropertyType[];+}): OutputSchemaV2 {+ const filteredEntries = Object.entries(outputSchema)+ .map(([key, field]) => {+ if (!isObject(field)) {+ return [key, field];+ }++ if (+ 'type' in field &&+ fieldTypesToExclude.some((fieldType) => fieldType === field.type)+ ) {+ return undefined;+ }++ if (+ 'isLeaf' in field &&+ field.isLeaf === false &&+ 'value' in field &&+ isObject(field.value)+ ) {+ return [+ key,+ {+ ...field,+ value: isRecordOutputSchemaV2(field.value)+ ? filterRecordOutputSchemaFieldsByType({+ outputSchema: field.value,+ fieldTypesToExclude,+ })+ : filterNonRecordOutputSchemaFieldsByType({+ outputSchema: field.value,+ fieldTypesToExclude,+ }),+ },+ ];+ }++ return [key, field];+ })+ .filter(isDefined);++ return Object.fromEntries(filteredEntries);+}++const filterOutputSchemaFieldsByType = ({+ outputSchema,+ fieldTypesToExclude,+}: {+ outputSchema: OutputSchemaV2;+ fieldTypesToExclude: InputSchemaPropertyType[];+}): OutputSchemaV2 => {+ if (isRecordOutputSchemaV2(outputSchema)) {+ return filterRecordOutputSchemaFieldsByType({+ outputSchema,+ fieldTypesToExclude,+ });+ }++ if (isLinkOutputSchema(outputSchema)) {+ return outputSchema;+ }++ return filterNonRecordOutputSchemaFieldsByType({+ outputSchema,+ fieldTypesToExclude,+ });+};+export const filterOutputSchema = ({shouldDisplayRecordFields,shouldDisplayRecordObjects,@@ -178,31 +279,28 @@ export const filterOutputSchema = ({return undefined;}- if (!shouldDisplayRecordObjects || shouldDisplayRecordFields) {- if (- isRecordOutputSchemaV2(outputSchema) &&- isDefined(fieldTypesToExclude)- ) {- return filterRecordOutputSchemaFieldsByType({+ const filteredOutputSchema = isDefined(fieldTypesToExclude)+ ? filterOutputSchemaFieldsByType({outputSchema,fieldTypesToExclude,- });- }+ })+ : outputSchema;- return outputSchema;+ if (!shouldDisplayRecordObjects || shouldDisplayRecordFields) {+ return filteredOutputSchema;}- if (isLinkOutputSchema(outputSchema)) {- return outputSchema;- } else if (isRecordOutputSchemaV2(outputSchema)) {+ if (isLinkOutputSchema(filteredOutputSchema)) {+ return filteredOutputSchema;+ } else if (isRecordOutputSchemaV2(filteredOutputSchema)) {return filterRecordOutputSchema({- outputSchema,+ outputSchema: filteredOutputSchema,shouldDisplayRecordFields,shouldDisplayRecordObjects,});- } else if (isBaseOutputSchemaV2(outputSchema)) {+ } else if (isBaseOutputSchemaV2(filteredOutputSchema)) {return filterBaseOutputSchema({- outputSchema,+ outputSchema: filteredOutputSchema,shouldDisplayRecordFields,shouldDisplayRecordObjects,});diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getStepItemIcon.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getStepItemIcon.tsindex ff7968751fe..1079d202c30 100644--- a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getStepItemIcon.ts+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getStepItemIcon.ts@@ -4,7 +4,7 @@ import { FieldMetadataType } from 'twenty-shared/types';export const getStepItemIcon = ({itemType,}: {- itemType: InputSchemaPropertyType;+ itemType?: InputSchemaPropertyType;}) => {if (itemType === 'string' || itemType === FieldMetadataType.TEXT) {return 'IconAbc';diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getWorkflowVariableRecordObjectDisplay.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getWorkflowVariableRecordObjectDisplay.tsnew file mode 100644index 00000000000..0958a7511b5--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getWorkflowVariableRecordObjectDisplay.ts@@ -0,0 +1,29 @@+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';+import { getObjectColorWithFallback } from '@/object-metadata/utils/getObjectColorWithFallback';+import { type RecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/RecordOutputSchemaV2';+import { isDefined } from 'twenty-shared/utils';++type WorkflowVariableRecordObjectMetadataItem = Pick<+ EnrichedObjectMetadataItem,+ 'labelSingular' | 'nameSingular' | 'icon' | 'color' | 'isSystem'+>;++export const getWorkflowVariableRecordObjectDisplay = ({+ recordObject,+ objectMetadataItem,+ objectNameSingularsToSelect,+}: {+ recordObject: RecordOutputSchemaV2['object'];+ objectMetadataItem: WorkflowVariableRecordObjectMetadataItem | undefined;+ objectNameSingularsToSelect?: string[];+}) => ({+ label: objectMetadataItem?.labelSingular ?? recordObject.label,+ icon: objectMetadataItem?.icon ?? recordObject.icon,+ iconColor: isDefined(objectMetadataItem)+ ? getObjectColorWithFallback(objectMetadataItem)+ : undefined,+ isSelectable:+ !isDefined(objectNameSingularsToSelect) ||+ (isDefined(objectMetadataItem) &&+ objectNameSingularsToSelect.includes(objectMetadataItem.nameSingular)),+});diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getWorkflowVariableSelectionFromSearchResult.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getWorkflowVariableSelectionFromSearchResult.tsnew file mode 100644index 00000000000..ec276c12c2f--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/getWorkflowVariableSelectionFromSearchResult.ts@@ -0,0 +1,14 @@+import { type WorkflowVariableSearchResult } from '@/workflow/workflow-variables/types/WorkflowVariableSearchResult';+import { type WorkflowVariableSelection } from '@/workflow/workflow-variables/types/WorkflowVariableSelection';+import { getVariableTemplateFromPath } from '@/workflow/workflow-variables/utils/getVariableTemplateFromPath';++export const getWorkflowVariableSelectionFromSearchResult = (+ result: WorkflowVariableSearchResult,+): WorkflowVariableSelection => ({+ rawVariableName: getVariableTemplateFromPath({+ stepId: result.stepId,+ path: result.path,+ }),+ stepId: result.stepId,+ isFullRecord: result.isFullRecord ?? false,+});diff --git a/packages/twenty-front/src/modules/workflow/workflow-variables/utils/searchWorkflowVariables.ts b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/searchWorkflowVariables.tsnew file mode 100644index 00000000000..4747e9db84a--- /dev/null+++ b/packages/twenty-front/src/modules/workflow/workflow-variables/utils/searchWorkflowVariables.ts@@ -0,0 +1,170 @@+import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';+import { isBaseOutputSchemaV2 } from '@/workflow/workflow-variables/types/guards/isBaseOutputSchemaV2';+import { isLinkOutputSchema } from '@/workflow/workflow-variables/types/guards/isLinkOutputSchema';+import { isRecordOutputSchemaV2 } from '@/workflow/workflow-variables/types/guards/isRecordOutputSchemaV2';+import {+ type OutputSchemaV2,+ type StepOutputSchemaV2,+} from '@/workflow/workflow-variables/types/StepOutputSchemaV2';+import { type WorkflowVariableSearchResult } from '@/workflow/workflow-variables/types/WorkflowVariableSearchResult';+import { getCurrentSubStepFromPath } from '@/workflow/workflow-variables/utils/getCurrentSubStepFromPath';+import { getStepHeaderLabel } from '@/workflow/workflow-variables/utils/getStepHeaderLabel';+import { getStepItemIcon } from '@/workflow/workflow-variables/utils/getStepItemIcon';+import { getWorkflowVariableRecordObjectDisplay } from '@/workflow/workflow-variables/utils/getWorkflowVariableRecordObjectDisplay';+import { getWorkflowVariableSpecialItems } from '@/workflow/workflow-variables/utils/getWorkflowVariableSpecialItems';+import { isDefined } from 'twenty-shared/utils';+import { isNonEmptyString, isObject } from '@sniptt/guards';++export const searchWorkflowVariables = ({+ steps,+ searchInputValue,+ shouldDisplaySpecialItems = true,+ currentPath = [],+ shouldDisplayRecordObjects = false,+ objectNameSingularsToSelect,+ objectMetadataItems = [],+}: {+ steps: StepOutputSchemaV2[];+ searchInputValue: string;+ shouldDisplaySpecialItems?: boolean;+ currentPath?: string[];+ shouldDisplayRecordObjects?: boolean;+ objectNameSingularsToSelect?: string[];+ objectMetadataItems?: Pick<+ EnrichedObjectMetadataItem,+ 'id' | 'labelSingular' | 'nameSingular' | 'icon' | 'color' | 'isSystem'+ >[];+}): WorkflowVariableSearchResult[] => {+ const search = searchInputValue.trim().toLowerCase();++ if (search.length === 0) {+ return [];+ }++ const objectMetadataItemsById = new Map(+ objectMetadataItems.map((item) => [item.id, item]),+ );++ return steps.flatMap((step) => {+ const results: WorkflowVariableSearchResult[] = [];++ const visitOutputSchema = (+ outputSchema: OutputSchemaV2,+ path: string[],+ labels: string[],+ ) => {+ const breadcrumb = [step.name, ...labels].join(' / ');++ if (+ shouldDisplayRecordObjects &&+ isRecordOutputSchemaV2(outputSchema) &&+ isDefined(outputSchema.object)+ ) {+ const object = outputSchema.object;+ const objectMetadataItem = objectMetadataItemsById.get(+ object.objectMetadataId,+ );+ const { label, icon, iconColor, isSelectable } =+ getWorkflowVariableRecordObjectDisplay({+ recordObject: object,+ objectMetadataItem,+ objectNameSingularsToSelect,+ });++ if (isSelectable && label.toLowerCase().includes(search)) {+ results.push({+ stepId: step.id,+ path: [...path, object.fieldIdName ?? 'id'],+ label,+ breadcrumb,+ icon,+ iconColor,+ isLeaf: true,+ isFullRecord: true,+ });+ }+ }++ const specialItems = shouldDisplaySpecialItems+ ? getWorkflowVariableSpecialItems({+ step,+ currentPath: path,+ searchInputValue: search,+ })+ : [];++ for (const specialItem of specialItems) {+ results.push({+ stepId: step.id,+ path: specialItem.path,+ label: specialItem.label,+ breadcrumb,+ icon: specialItem.iconName,+ isLeaf: true,+ });+ }++ if (isLinkOutputSchema(outputSchema)) {+ const label = outputSchema.link.label;++ if (isDefined(label) && label.toLowerCase().includes(search)) {+ results.push({+ stepId: step.id,+ path,+ label,+ breadcrumb,+ isLeaf: false,+ });+ }++ return;+ }++ const fields = (() => {+ if (isRecordOutputSchemaV2(outputSchema)) {+ return outputSchema.fields;+ }++ if (isBaseOutputSchemaV2(outputSchema)) {+ return outputSchema;+ }++ return {};+ })();++ for (const [key, field] of Object.entries(fields)) {+ if (!isObject(field)) {+ continue;+ }++ const label = isNonEmptyString(field.label) ? field.label : key;+ const fieldPath = [...path, key];++ if (label.toLowerCase().includes(search)) {+ results.push({+ stepId: step.id,+ path: fieldPath,+ label,+ breadcrumb,+ icon: field.icon ?? getStepItemIcon({ itemType: field.type }),+ isLeaf: field.isLeaf,+ });+ }++ if (!field.isLeaf && isDefined(field.value)) {+ visitOutputSchema(field.value, fieldPath, [...labels, label]);+ }+ }+ };++ visitOutputSchema(+ getCurrentSubStepFromPath(step, currentPath),+ currentPath,+ currentPath.map((_, index) =>+ getStepHeaderLabel(step, currentPath.slice(0, index + 1)),+ ),+ );++ return results;+ });+};