Skip to content

The open alternative to Salesforce, designed for AI.

Keep validation rules in sync with metadata events (#27302)

Thomas Trompettef1c18aca612b
diff --git a/packages/twenty-front/src/modules/validation-rules/hooks/__tests__/useValidationRules.test.tsx b/packages/twenty-front/src/modules/validation-rules/hooks/__tests__/useValidationRules.test.tsx
new file mode 100644
index 00000000000..ade5b65fa16
--- /dev/null
+++ b/packages/twenty-front/src/modules/validation-rules/hooks/__tests__/useValidationRules.test.tsx
@@ -0,0 +1,232 @@
+import { MockedProvider } from '@apollo/client/testing/react';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import { type ReactNode } from 'react';
+
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { dispatchMetadataOperationBrowserEvent } from '@/browser-event/utils/dispatchMetadataOperationBrowserEvent';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+import { useValidationRules } from '@/validation-rules/hooks/useValidationRules';
+import { type ValidationRule } from '@/validation-rules/types/ValidationRule';
+import {
+ AllMetadataName,
+ FeatureFlagKey,
+ FindManyValidationRulesDocument,
+} from '~/generated-metadata/graphql';
+import { mockCurrentWorkspace } from '~/testing/mock-data/users';
+
+const OBJECT_METADATA_ID = '20202020-0000-4000-8000-000000000001';
+const OTHER_OBJECT_METADATA_ID = '20202020-0000-4000-8000-000000000002';
+
+const ACTIVE_VALIDATION_RULE: ValidationRule = {
+ id: '20202020-0000-4000-8000-000000000010',
+ objectMetadataId: OBJECT_METADATA_ID,
+ name: 'No won deals yet',
+ description: null,
+ icon: 'IconListCheck',
+ errorFieldMetadataId: null,
+ expression: 'stage != "WON"',
+ message: 'Deals cannot be won yet',
+ isActive: true,
+};
+
+const DISABLED_VALIDATION_RULE: ValidationRule = {
+ ...ACTIVE_VALIDATION_RULE,
+ isActive: false,
+};
+
+const SECOND_VALIDATION_RULE: ValidationRule = {
+ ...ACTIVE_VALIDATION_RULE,
+ id: '20202020-0000-4000-8000-000000000011',
+ name: 'Amount is set',
+ expression: 'amount != null',
+};
+
+const buildValidationRulesMock = (validationRules: ValidationRule[]) => ({
+ request: {
+ query: FindManyValidationRulesDocument,
+ variables: { objectMetadataId: OBJECT_METADATA_ID },
+ },
+ delay: jest.fn(() => 0),
+ result: jest.fn(() => ({
+ data: {
+ validationRules: validationRules.map((validationRule) => ({
+ __typename: 'ValidationRule' as const,
+ ...validationRule,
+ })),
+ },
+ })),
+});
+
+const renderUseValidationRules = ({
+ mocks,
+ isValidationRulesEnabled = true,
+}: {
+ mocks: ReturnType<typeof buildValidationRulesMock>[];
+ isValidationRulesEnabled?: boolean;
+}) => {
+ resetJotaiStore();
+ jotaiStore.set(currentWorkspaceState.atom, {
+ ...mockCurrentWorkspace,
+ featureFlags: [
+ {
+ key: FeatureFlagKey.IS_VALIDATION_RULES_ENABLED,
+ value: isValidationRulesEnabled,
+ },
+ ],
+ });
+
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <JotaiProvider store={jotaiStore}>
+ <MockedProvider mocks={mocks}>{children}</MockedProvider>
+ </JotaiProvider>
+ );
+
+ return renderHook(
+ () => useValidationRules({ objectMetadataId: OBJECT_METADATA_ID }),
+ { wrapper },
+ );
+};
+
+const dispatchValidationRuleUpdate = (updatedRecord: ValidationRule) =>
+ dispatchMetadataOperationBrowserEvent<ValidationRule>({
+ metadataName: AllMetadataName.validationRule,
+ operation: { type: 'update', updatedRecord, updatedFields: ['isActive'] },
+ });
+
+const flushPendingRequests = () =>
+ act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+
+describe('useValidationRules', () => {
+ it('should stop enforcing a rule another session disabled while the form is open', async () => {
+ const refetchMock = buildValidationRulesMock([DISABLED_VALIDATION_RULE]);
+
+ const { result } = renderUseValidationRules({
+ mocks: [buildValidationRulesMock([ACTIVE_VALIDATION_RULE]), refetchMock],
+ });
+
+ await waitFor(() =>
+ expect(result.current.validationRules).toMatchObject([
+ { id: ACTIVE_VALIDATION_RULE.id, isActive: true },
+ ]),
+ );
+
+ act(() => {
+ dispatchValidationRuleUpdate(DISABLED_VALIDATION_RULE);
+ });
+
+ await waitFor(() =>
+ expect(result.current.validationRules).toMatchObject([
+ { id: ACTIVE_VALIDATION_RULE.id, isActive: false },
+ ]),
+ );
+ expect(refetchMock.result).toHaveBeenCalledTimes(1);
+ });
+
+ it('should drop a rule another session deleted while the form is open', async () => {
+ const { result } = renderUseValidationRules({
+ mocks: [
+ buildValidationRulesMock([ACTIVE_VALIDATION_RULE]),
+ buildValidationRulesMock([]),
+ ],
+ });
+
+ await waitFor(() => expect(result.current.validationRules).toHaveLength(1));
+
+ act(() => {
+ dispatchMetadataOperationBrowserEvent<ValidationRule>({
+ metadataName: AllMetadataName.validationRule,
+ operation: {
+ type: 'delete',
+ deletedRecordId: ACTIVE_VALIDATION_RULE.id,
+ },
+ });
+ });
+
+ await waitFor(() => expect(result.current.validationRules).toHaveLength(0));
+ });
+
+ it('should refetch once when a field migration updates several rules at once', async () => {
+ const refetchMock = buildValidationRulesMock([
+ DISABLED_VALIDATION_RULE,
+ { ...SECOND_VALIDATION_RULE, isActive: false },
+ ]);
+
+ const { result } = renderUseValidationRules({
+ mocks: [
+ buildValidationRulesMock([
+ ACTIVE_VALIDATION_RULE,
+ SECOND_VALIDATION_RULE,
+ ]),
+ refetchMock,
+ ],
+ });
+
+ await waitFor(() => expect(result.current.validationRules).toHaveLength(2));
+
+ act(() => {
+ dispatchValidationRuleUpdate(DISABLED_VALIDATION_RULE);
+ dispatchValidationRuleUpdate({
+ ...SECOND_VALIDATION_RULE,
+ isActive: false,
+ });
+ });
+
+ await waitFor(() =>
+ expect(result.current.validationRules).toMatchObject([
+ { id: ACTIVE_VALIDATION_RULE.id, isActive: false },
+ { id: SECOND_VALIDATION_RULE.id, isActive: false },
+ ]),
+ );
+ expect(refetchMock.result).toHaveBeenCalledTimes(1);
+ });
+
+ it('should not refetch when a rule of another object changes', async () => {
+ const refetchMock = buildValidationRulesMock([]);
+
+ const { result } = renderUseValidationRules({
+ mocks: [buildValidationRulesMock([ACTIVE_VALIDATION_RULE]), refetchMock],
+ });
+
+ await waitFor(() => expect(result.current.validationRules).toHaveLength(1));
+
+ act(() => {
+ dispatchValidationRuleUpdate({
+ ...ACTIVE_VALIDATION_RULE,
+ id: '20202020-0000-4000-8000-000000000012',
+ objectMetadataId: OTHER_OBJECT_METADATA_ID,
+ isActive: false,
+ });
+ });
+
+ await flushPendingRequests();
+
+ expect(refetchMock.delay).not.toHaveBeenCalled();
+ expect(result.current.validationRules).toHaveLength(1);
+ });
+
+ it('should neither load nor listen when the feature flag is disabled', async () => {
+ const validationRulesMock = buildValidationRulesMock([
+ ACTIVE_VALIDATION_RULE,
+ ]);
+
+ const { result } = renderUseValidationRules({
+ mocks: [validationRulesMock],
+ isValidationRulesEnabled: false,
+ });
+
+ act(() => {
+ dispatchValidationRuleUpdate(DISABLED_VALIDATION_RULE);
+ });
+
+ await flushPendingRequests();
+
+ expect(validationRulesMock.delay).not.toHaveBeenCalled();
+ expect(result.current.validationRules).toEqual([]);
+ });
+});
diff --git a/packages/twenty-front/src/modules/validation-rules/hooks/useValidationRules.ts b/packages/twenty-front/src/modules/validation-rules/hooks/useValidationRules.ts
index 572acb829b3..81abc8b0f5b 100644
--- a/packages/twenty-front/src/modules/validation-rules/hooks/useValidationRules.ts
+++ b/packages/twenty-front/src/modules/validation-rules/hooks/useValidationRules.ts
@@ -1,8 +1,14 @@
import { useQuery } from '@apollo/client/react';
+import { useCallback } from 'react';
import { isNonEmptyString } from 'twenty-shared/utils';
+import { useListenToMetadataOperationBrowserEvent } from '@/browser-event/hooks/useListenToMetadataOperationBrowserEvent';
+import { type MetadataOperationBrowserEventDetail } from '@/browser-event/types/MetadataOperationBrowserEventDetail';
+import { type ValidationRule } from '@/validation-rules/types/ValidationRule';
+import { shouldRefetchValidationRulesOnOperation } from '@/validation-rules/utils/shouldRefetchValidationRulesOnOperation';
import { useIsFeatureEnabled } from '@/workspace/hooks/useIsFeatureEnabled';
import {
+ AllMetadataName,
FeatureFlagKey,
FindManyValidationRulesDocument,
} from '~/generated-metadata/graphql';
@@ -16,9 +22,32 @@ export const useValidationRules = ({
FeatureFlagKey.IS_VALIDATION_RULES_ENABLED,
);
+ const skip = !isValidationRulesEnabled || !isNonEmptyString(objectMetadataId);
+
const { data, loading, refetch } = useQuery(FindManyValidationRulesDocument, {
variables: { objectMetadataId },
- skip: !isValidationRulesEnabled || !isNonEmptyString(objectMetadataId),
+ skip,
+ });
+
+ const refetchOnValidationRuleOperation = useCallback(
+ ({ operation }: MetadataOperationBrowserEventDetail<ValidationRule>) => {
+ if (
+ shouldRefetchValidationRulesOnOperation({
+ operation,
+ objectMetadataId,
+ validationRules: data?.validationRules ?? [],
+ })
+ ) {
+ void refetch();
+ }
+ },
+ [data, objectMetadataId, refetch],
+ );
+
+ useListenToMetadataOperationBrowserEvent<ValidationRule>({
+ metadataName: AllMetadataName.validationRule,
+ onMetadataOperationBrowserEvent: refetchOnValidationRuleOperation,
+ skip,
});
return {
diff --git a/packages/twenty-front/src/modules/validation-rules/utils/__tests__/shouldRefetchValidationRulesOnOperation.test.ts b/packages/twenty-front/src/modules/validation-rules/utils/__tests__/shouldRefetchValidationRulesOnOperation.test.ts
new file mode 100644
index 00000000000..2b401e88965
--- /dev/null
+++ b/packages/twenty-front/src/modules/validation-rules/utils/__tests__/shouldRefetchValidationRulesOnOperation.test.ts
@@ -0,0 +1,92 @@
+import { type ValidationRule } from '@/validation-rules/types/ValidationRule';
+import { shouldRefetchValidationRulesOnOperation } from '@/validation-rules/utils/shouldRefetchValidationRulesOnOperation';
+
+const OBJECT_METADATA_ID = '20202020-0000-4000-8000-000000000001';
+const OTHER_OBJECT_METADATA_ID = '20202020-0000-4000-8000-000000000002';
+
+const LOADED_VALIDATION_RULE: ValidationRule = {
+ id: '20202020-0000-4000-8000-000000000010',
+ objectMetadataId: OBJECT_METADATA_ID,
+ name: 'No won deals yet',
+ description: null,
+ icon: 'IconListCheck',
+ errorFieldMetadataId: null,
+ expression: 'stage != "WON"',
+ message: 'Deals cannot be won yet',
+ isActive: true,
+};
+
+describe('shouldRefetchValidationRulesOnOperation', () => {
+ it('should refetch when a rule is created on the object', () => {
+ expect(
+ shouldRefetchValidationRulesOnOperation({
+ operation: {
+ type: 'create',
+ createdRecord: {
+ ...LOADED_VALIDATION_RULE,
+ id: '20202020-0000-4000-8000-000000000011',
+ },
+ },
+ objectMetadataId: OBJECT_METADATA_ID,
+ validationRules: [LOADED_VALIDATION_RULE],
+ }),
+ ).toBe(true);
+ });
+
+ it('should refetch when a rule of the object is updated', () => {
+ expect(
+ shouldRefetchValidationRulesOnOperation({
+ operation: {
+ type: 'update',
+ updatedRecord: { ...LOADED_VALIDATION_RULE, isActive: false },
+ updatedFields: ['isActive'],
+ },
+ objectMetadataId: OBJECT_METADATA_ID,
+ validationRules: [LOADED_VALIDATION_RULE],
+ }),
+ ).toBe(true);
+ });
+
+ it('should not refetch when a rule of another object changes', () => {
+ expect(
+ shouldRefetchValidationRulesOnOperation({
+ operation: {
+ type: 'update',
+ updatedRecord: {
+ ...LOADED_VALIDATION_RULE,
+ id: '20202020-0000-4000-8000-000000000012',
+ objectMetadataId: OTHER_OBJECT_METADATA_ID,
+ },
+ },
+ objectMetadataId: OBJECT_METADATA_ID,
+ validationRules: [LOADED_VALIDATION_RULE],
+ }),
+ ).toBe(false);
+ });
+
+ it('should refetch when a loaded rule is deleted', () => {
+ expect(
+ shouldRefetchValidationRulesOnOperation({
+ operation: {
+ type: 'delete',
+ deletedRecordId: LOADED_VALIDATION_RULE.id,
+ },
+ objectMetadataId: OBJECT_METADATA_ID,
+ validationRules: [LOADED_VALIDATION_RULE],
+ }),
+ ).toBe(true);
+ });
+
+ it('should not refetch when a rule that is not loaded is deleted', () => {
+ expect(
+ shouldRefetchValidationRulesOnOperation({
+ operation: {
+ type: 'delete',
+ deletedRecordId: '20202020-0000-4000-8000-000000000013',
+ },
+ objectMetadataId: OBJECT_METADATA_ID,
+ validationRules: [LOADED_VALIDATION_RULE],
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-front/src/modules/validation-rules/utils/shouldRefetchValidationRulesOnOperation.ts b/packages/twenty-front/src/modules/validation-rules/utils/shouldRefetchValidationRulesOnOperation.ts
new file mode 100644
index 00000000000..aea88f9eac7
--- /dev/null
+++ b/packages/twenty-front/src/modules/validation-rules/utils/shouldRefetchValidationRulesOnOperation.ts
@@ -0,0 +1,23 @@
+import { type MetadataOperation } from '@/browser-event/types/MetadataOperation';
+import { type ValidationRule } from '@/validation-rules/types/ValidationRule';
+
+export const shouldRefetchValidationRulesOnOperation = ({
+ operation,
+ objectMetadataId,
+ validationRules,
+}: {
+ operation: MetadataOperation<ValidationRule>;
+ objectMetadataId: string;
+ validationRules: ValidationRule[];
+}): boolean => {
+ switch (operation.type) {
+ case 'create':
+ return operation.createdRecord.objectMetadataId === objectMetadataId;
+ case 'update':
+ return operation.updatedRecord.objectMetadataId === objectMetadataId;
+ case 'delete':
+ return validationRules.some(
+ (validationRule) => validationRule.id === operation.deletedRecordId,
+ );
+ }
+};
diff --git a/packages/twenty-front/src/pages/settings/data-model/validation-rules/SettingsObjectValidationRuleEdit.tsx b/packages/twenty-front/src/pages/settings/data-model/validation-rules/SettingsObjectValidationRuleEdit.tsx
index 4c60c58227e..33696b8caeb 100644
--- a/packages/twenty-front/src/pages/settings/data-model/validation-rules/SettingsObjectValidationRuleEdit.tsx
+++ b/packages/twenty-front/src/pages/settings/data-model/validation-rules/SettingsObjectValidationRuleEdit.tsx
@@ -27,16 +27,12 @@ export const SettingsObjectValidationRuleEdit = () => {
return <NotFound />;
}
- if (loading) {
- return null;
- }
-
const validationRule = validationRules.find(
(candidate) => candidate.id === validationRuleId,
);
if (!isDefined(validationRule)) {
- return <NotFound />;
+ return loading ? null : <NotFound />;
}
return (