Skip to content

The open alternative to Salesforce, designed for AI.

10.6 KB
Raw Blame
import { styled } from '@linaria/react';
import { Trans, useLingui } from '@lingui/react/macro';
import { isNonEmptyString } from '@sniptt/guards';
import { Fragment, useState } from 'react';
import { VALIDATION_RULE_NOW_VARIABLE_NAME } from 'twenty-shared/constants';
import { type ValidationRuleFieldDescriptor } from 'twenty-shared/types';
import {
  compileValidationRuleExpression,
  evaluateValidationRuleExpression,
  isDefined,
  parseValidationRuleExpression,
} from 'twenty-shared/utils';
import { InlineBanner } from 'twenty-ui/components/feedback';
import { LightIconButton } from 'twenty-ui/components/input';
import { IconChevronDown, IconChevronUp } from 'twenty-ui/icon';
import { useIcons } from 'twenty-ui/icon/provider';
import { Status } from 'twenty-ui/primitives/data-display';
import { Card, Tooltip } from 'twenty-ui/primitives/surfaces';
import { themeCssVariables, useTheme } from 'twenty-ui/theme';

import { useObjectMetadataItems } from '@/object-metadata/hooks/useObjectMetadataItems';
import { type EnrichedObjectMetadataItem } from '@/object-metadata/types/EnrichedObjectMetadataItem';
import { RecordChip } from '@/object-record/components/RecordChip';
import { generateDepthRecordGqlFieldsFromObject } from '@/object-record/graphql/record-gql-fields/utils/generateDepthRecordGqlFieldsFromObject';
import { useFindManyRecords } from '@/object-record/hooks/useFindManyRecords';
import { StyledFormCardTitle } from '@/settings/data-model/fields/components/StyledFormCardTitle';
import { TooltipDelay } from '@/ui/layout/tooltip/constants/TooltipDelay';
import { type ValidationRuleEditorField } from '@/validation-rules/types/ValidationRuleEditorField';
import { buildValidationRulePreviewRelationGqlFields } from '@/validation-rules/utils/buildValidationRulePreviewRelationGqlFields';
import { formatValidationRulePreviewValue } from '@/validation-rules/utils/formatValidationRulePreviewValue';
import { getValidationRuleEditorFieldChipLabel } from '@/validation-rules/utils/getValidationRuleEditorFieldChipLabel';
import { getValidationRuleErrorMessage } from '@/validation-rules/utils/getValidationRuleErrorMessage';
import { getValidationRulePreviewValue } from '@/validation-rules/utils/getValidationRulePreviewValue';

const PREVIEW_RECORD_COUNT = 3;

const StyledPreviewHeader = styled.div`
  align-items: center;
  display: flex;
  gap: ${themeCssVariables.spacing[2]};
  justify-content: space-between;
  margin-bottom: ${themeCssVariables.spacing[4]};
  min-height: 24px;
`;

const StyledPreviewTitle = styled(StyledFormCardTitle)`
  margin-bottom: 0;
`;

const StyledRecordHeader = styled.div`
  align-items: center;
  display: flex;
  gap: ${themeCssVariables.spacing[2]};
  justify-content: space-between;
  min-width: 0;
`;

const StyledRecord = styled.div`
  display: flex;
  min-width: 0;
  overflow: hidden;
`;

const StyledStatus = styled.span`
  flex-shrink: 0;
`;

const StyledNavigation = styled.div`
  align-items: center;
  color: ${themeCssVariables.font.color.tertiary};
  display: flex;
  flex-shrink: 0;
  font-size: ${themeCssVariables.font.size.sm};
  gap: ${themeCssVariables.spacing[1]};
`;

const StyledFieldValues = styled.div`
  column-gap: ${themeCssVariables.spacing[2]};
  display: grid;
  font-size: ${themeCssVariables.font.size.md};
  grid-template-columns: fit-content(50%) minmax(0, 1fr);
  line-height: 24px;
  margin-top: ${themeCssVariables.spacing[2]};
  row-gap: ${themeCssVariables.spacing[1]};
`;

const StyledFieldLabel = styled.div`
  align-items: center;
  color: ${themeCssVariables.font.color.tertiary};
  display: flex;
  gap: ${themeCssVariables.spacing[1]};
  min-width: 0;
  overflow-wrap: anywhere;
`;

const StyledValue = styled.span<{ isEmpty: boolean }>`
  color: ${({ isEmpty }) =>
    isEmpty
      ? themeCssVariables.font.color.light
      : themeCssVariables.font.color.primary};
  min-width: 0;
  overflow-wrap: anywhere;
`;

const StyledMuted = styled.div`
  color: ${themeCssVariables.font.color.light};
`;

const StyledFieldValuesPlaceholder = styled(StyledMuted)`
  font-size: ${themeCssVariables.font.size.md};
  line-height: 24px;
  margin-top: ${themeCssVariables.spacing[2]};
`;

const StyledErrorMessage = styled.div`
  margin-top: ${themeCssVariables.spacing[3]};
`;

type SettingsValidationRulePreviewProps = {
  objectMetadataItem: EnrichedObjectMetadataItem;
  fields: ValidationRuleFieldDescriptor[];
  editorFields: ValidationRuleEditorField[];
  expression: string;
  message: string;
};

export const SettingsValidationRulePreview = ({
  objectMetadataItem,
  fields,
  editorFields,
  expression,
  message,
}: SettingsValidationRulePreviewProps) => {
  const { t } = useLingui();
  const theme = useTheme();
  const { getIcon } = useIcons();
  const { objectMetadataItems } = useObjectMetadataItems();
  const [recordIndex, setRecordIndex] = useState(0);

  const compilationResult = compileValidationRuleExpression({
    expression,
    fields,
  });

  const { records, loading } = useFindManyRecords({
    objectNameSingular: objectMetadataItem.nameSingular,
    limit: PREVIEW_RECORD_COUNT,
    orderBy: [{ createdAt: 'DescNullsLast' }],
    recordGqlFields: {
      ...generateDepthRecordGqlFieldsFromObject({
        objectMetadataItems,
        objectMetadataItem,
        depth: 0,
      }),
      ...buildValidationRulePreviewRelationGqlFields({
        bindingPaths: compilationResult.isValid
          ? Object.keys(compilationResult.bindings)
          : [],
        fields,
      }),
    },
  });

  const previewTitle = (
    <StyledPreviewTitle>
      <Trans>Preview</Trans>
    </StyledPreviewTitle>
  );

  if (loading) {
    return <StyledPreviewHeader>{previewTitle}</StyledPreviewHeader>;
  }

  const record = records[Math.min(recordIndex, records.length - 1)];

  if (!isDefined(record)) {
    return (
      <>
        <StyledPreviewHeader>{previewTitle}</StyledPreviewHeader>
        <Card.Root fullWidth>
          <Card.Content>
            <StyledMuted>
              {t`Create a few ${objectMetadataItem.labelPlural} to preview this rule on real records.`}
            </StyledMuted>
          </Card.Content>
        </Card.Root>
      </>
    );
  }

  const referencedPaths = compilationResult.isValid
    ? [
        ...new Set(
          parseValidationRuleExpression(expression).variables({
            withMembers: true,
          }),
        ),
      ].filter((path) => path !== VALIDATION_RULE_NOW_VARIABLE_NAME)
    : [];

  const evaluationResult = compilationResult.isValid
    ? evaluateValidationRuleExpression({
        expression,
        record,
        fields,
        now: new Date().toISOString(),
      })
    : undefined;

  const trimmedMessage = message.trim();
  const isErrorMessageVisible =
    evaluationResult?.status === 'failed' && isNonEmptyString(trimmedMessage);

  const renderStatus = () => {
    if (!isDefined(evaluationResult)) {
      return null;
    }

    switch (evaluationResult.status) {
      case 'passed':
        return (
          <StyledStatus>
            <Status color="green">{t`Valid`}</Status>
          </StyledStatus>
        );
      case 'failed':
        return (
          <StyledStatus>
            <Status color="red">{t`Blocked`}</Status>
          </StyledStatus>
        );
      case 'errored':
        return (
          <Tooltip
            delay={TooltipDelay.mediumDelay}
            content={getValidationRuleErrorMessage(evaluationResult)}
            side="top"
          >
            <StyledStatus tabIndex={0}>
              <Status color="orange">{t`Error`}</Status>
            </StyledStatus>
          </Tooltip>
        );
    }
  };

  const displayedRecordNumber = records.indexOf(record) + 1;
  const recordCount = records.length;

  return (
    <>
      <StyledPreviewHeader>
        {previewTitle}
        <StyledNavigation>
          {t`Record ${displayedRecordNumber} of ${recordCount}`}
          <LightIconButton
            aria-label={t`Previous record`}
            disabled={displayedRecordNumber === 1}
            onClick={() => setRecordIndex(displayedRecordNumber - 2)}
          >
            <IconChevronUp />
          </LightIconButton>
          <LightIconButton
            aria-label={t`Next record`}
            disabled={displayedRecordNumber === recordCount}
            onClick={() => setRecordIndex(displayedRecordNumber)}
          >
            <IconChevronDown />
          </LightIconButton>
        </StyledNavigation>
      </StyledPreviewHeader>
      <Card.Root fullWidth>
        <Card.Content>
          <StyledRecordHeader>
            <StyledRecord>
              <RecordChip
                objectNameSingular={objectMetadataItem.nameSingular}
                record={record}
                forceDisableClick
              />
            </StyledRecord>
            {renderStatus()}
          </StyledRecordHeader>
          {referencedPaths.length === 0 ? (
            <StyledFieldValuesPlaceholder>
              {compilationResult.isValid
                ? t`This condition doesn't read any field.`
                : t`Fields used in the condition show their values here.`}
            </StyledFieldValuesPlaceholder>
          ) : (
            <StyledFieldValues>
              {referencedPaths.map((path) => {
                const editorField = editorFields.find(
                  (candidate) => candidate.path === path,
                );
                const fieldLabel = isDefined(editorField)
                  ? getValidationRuleEditorFieldChipLabel(editorField)
                  : path;
                const FieldIcon = isDefined(editorField)
                  ? getIcon(editorField.iconName)
                  : undefined;
                const formattedValue = formatValidationRulePreviewValue(
                  getValidationRulePreviewValue(record, path),
                );

                return (
                  <Fragment key={path}>
                    <StyledFieldLabel>
                      {isDefined(FieldIcon) && (
                        <FieldIcon
                          size={theme.icon.size.md}
                          stroke={theme.icon.stroke.sm}
                        />
                      )}
                      {fieldLabel}
                    </StyledFieldLabel>
                    <StyledValue isEmpty={formattedValue.length === 0}>
                      {formattedValue.length > 0 ? formattedValue : t`Empty`}
                    </StyledValue>
                  </Fragment>
                );
              })}
            </StyledFieldValues>
          )}
          {isErrorMessageVisible && (
            <StyledErrorMessage>
              <InlineBanner status="error" embedded>
                {trimmedMessage}
              </InlineBanner>
            </StyledErrorMessage>
          )}
        </Card.Content>
      </Card.Root>
    </>
  );
};