Skip to content

The open alternative to Salesforce, designed for AI.

1.6 KB
Raw Blame
import { useAtomFamilySelectorValue } from '@/ui/utilities/state/jotai/hooks/useAtomFamilySelectorValue';
import { useFlowOrThrow } from '@/workflow/hooks/useFlowOrThrow';
import { useWorkflowVersionIdOrThrow } from '@/workflow/hooks/useWorkflowVersionIdOrThrow';
import { stepsOutputSchemaFamilySelector } from '@/workflow/states/selectors/stepsOutputSchemaFamilySelector';
import { searchVariableThroughOutputSchemaV2 } from '@/workflow/workflow-variables/utils/searchVariableThroughOutputSchemaV2';
import { isDefined } from 'twenty-shared/utils';
import {
  TRIGGER_STEP_ID,
  type VariableSearchResult,
} from 'twenty-shared/workflow';

export const useSearchVariable = ({
  stepId,
  rawVariableName,
  isFullRecord,
}: {
  stepId: string;
  rawVariableName: string;
  isFullRecord: boolean;
}): VariableSearchResult => {
  const workflowVersionId = useWorkflowVersionIdOrThrow();
  const flow = useFlowOrThrow();
  const [stepOutputSchema] = useAtomFamilySelectorValue(
    stepsOutputSchemaFamilySelector,
    {
      workflowVersionId,
      stepIds: [stepId],
    },
  );

  if (!isDefined(stepOutputSchema)) {
    return {
      variableLabel: undefined,
      variablePathLabel: undefined,
    };
  }

  const stepType =
    stepId === TRIGGER_STEP_ID
      ? flow.trigger?.type
      : flow.steps?.find((step) => step.id === stepId)?.type;

  if (!isDefined(stepType)) {
    return {
      variableLabel: undefined,
      variablePathLabel: undefined,
    };
  }

  return searchVariableThroughOutputSchemaV2({
    stepOutputSchema,
    stepType,
    rawVariableName,
    isFullRecord,
  });
};