The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
fix(server,shared): validate view filter values on app manifest sync (#23848)
Thomas Trompette532330ed1e27
diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-view-filter-validator.service.spec.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-view-filter-validator.service.spec.tsnew file mode 100644index 00000000000..2318e0e7fea--- /dev/null+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/__tests__/flat-view-filter-validator.service.spec.ts@@ -0,0 +1,168 @@+import { FieldMetadataType, ViewFilterOperand } from 'twenty-shared/types';++import { FlatViewFilterValidatorService } from 'src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-view-filter-validator.service';++const VIEW_UNIVERSAL_IDENTIFIER = '00000000-0000-4000-8000-0000000000c1';+const FIELD_UNIVERSAL_IDENTIFIER = '00000000-0000-4000-8000-0000000000d1';+const VIEW_FILTER_UNIVERSAL_IDENTIFIER = '00000000-0000-4000-8000-0000000000e1';++const mapsFrom = (+ entities: { universalIdentifier: string; [key: string]: unknown }[],+) => ({+ byUniversalIdentifier: Object.fromEntries(+ entities.map((entity) => [entity.universalIdentifier, entity]),+ ),+});++const buildFlatViewFilter = ({+ operand,+ value,+ subFieldName = null,+}: {+ operand: ViewFilterOperand;+ value: unknown;+ subFieldName?: string | null;+}) => ({+ universalIdentifier: VIEW_FILTER_UNIVERSAL_IDENTIFIER,+ viewUniversalIdentifier: VIEW_UNIVERSAL_IDENTIFIER,+ fieldMetadataUniversalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,+ viewFilterGroupUniversalIdentifier: null,+ relationTargetFieldMetadataUniversalIdentifier: null,+ operand,+ value,+ subFieldName,+});++const buildCreationArgs = ({+ fieldType,+ operand,+ value,+ subFieldName,+}: {+ fieldType: FieldMetadataType;+ operand: ViewFilterOperand;+ value: unknown;+ subFieldName?: string | null;+}) =>+ ({+ flatEntityToValidate: buildFlatViewFilter({ operand, value, subFieldName }),+ optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {+ flatViewFilterMaps: mapsFrom([]),+ flatViewMaps: mapsFrom([+ { universalIdentifier: VIEW_UNIVERSAL_IDENTIFIER },+ ]),+ flatFieldMetadataMaps: mapsFrom([+ {+ universalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,+ type: fieldType,+ label: 'Expires At',+ },+ ]),+ flatViewFilterGroupMaps: mapsFrom([]),+ },+ }) as unknown as Parameters<+ FlatViewFilterValidatorService['validateFlatViewFilterCreation']+ >[0];++const buildUpdateArgs = ({+ fieldType,+ operand,+ flatEntityUpdate,+}: {+ fieldType: FieldMetadataType;+ operand: ViewFilterOperand;+ flatEntityUpdate: Record<string, unknown>;+}) =>+ ({+ universalIdentifier: VIEW_FILTER_UNIVERSAL_IDENTIFIER,+ flatEntityUpdate,+ optimisticFlatEntityMapsAndRelatedFlatEntityMaps: {+ flatViewFilterMaps: mapsFrom([+ buildFlatViewFilter({ operand, value: 'NEXT_30_DAY' }),+ ]),+ flatFieldMetadataMaps: mapsFrom([+ {+ universalIdentifier: FIELD_UNIVERSAL_IDENTIFIER,+ type: fieldType,+ label: 'Expires At',+ },+ ]),+ flatViewFilterGroupMaps: mapsFrom([]),+ },+ }) as unknown as Parameters<+ FlatViewFilterValidatorService['validateFlatViewFilterUpdate']+ >[0];++describe('FlatViewFilterValidatorService', () => {+ let service: FlatViewFilterValidatorService;++ beforeEach(() => {+ service = new FlatViewFilterValidatorService();+ });++ describe('value validation on creation', () => {+ it('should accept a value still being filled in', () => {+ const result = service.validateFlatViewFilterCreation(+ buildCreationArgs({+ fieldType: FieldMetadataType.DATE,+ operand: ViewFilterOperand.IS_RELATIVE,+ value: '',+ }),+ );++ expect(result.errors).toEqual([]);+ });++ it('should not validate a value for an operand expecting none', () => {+ const result = service.validateFlatViewFilterCreation(+ buildCreationArgs({+ fieldType: FieldMetadataType.DATE,+ operand: ViewFilterOperand.IS_TODAY,+ value: 'anything',+ }),+ );++ expect(result.errors).toEqual([]);+ });+ });++ describe('value validation on update', () => {+ it('should reject an invalid value being written', () => {+ const result = service.validateFlatViewFilterUpdate(+ buildUpdateArgs({+ fieldType: FieldMetadataType.DATE,+ operand: ViewFilterOperand.IS_RELATIVE,+ flatEntityUpdate: {+ value: { direction: 'NEXT', amount: 30, unit: 'DAY' },+ },+ }),+ );++ expect(result.errors).toHaveLength(1);+ });++ it('should revalidate when the sub field changes the applicable schema', () => {+ const result = service.validateFlatViewFilterUpdate(+ buildUpdateArgs({+ fieldType: FieldMetadataType.CURRENCY,+ operand: ViewFilterOperand.IS,+ flatEntityUpdate: { subFieldName: 'currencyCode' },+ }),+ );++ expect(result.errors).toHaveLength(1);+ });++ it('should not validate the value when it is not part of the update', () => {+ const result = service.validateFlatViewFilterUpdate(+ buildUpdateArgs({+ fieldType: FieldMetadataType.DATE,+ operand: ViewFilterOperand.IS_RELATIVE,+ flatEntityUpdate: { positionInViewFilterGroup: 2 },+ }),+ );++ expect(result.errors).toEqual([]);+ });+ });+});diff --git a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-view-filter-validator.service.ts b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-view-filter-validator.service.tsindex 824aa3e349b..675152e3871 100644--- a/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-view-filter-validator.service.ts+++ b/packages/twenty-server/src/engine/workspace-manager/workspace-migration/workspace-migration-builder/validators/services/flat-view-filter-validator.service.ts@@ -1,6 +1,7 @@import { Injectable } from '@nestjs/common';import { msg, t } from '@lingui/core/macro';+import { isNonEmptyString } from '@sniptt/guards';import { ALL_METADATA_NAME } from 'twenty-shared/metadata';import {FieldMetadataType,@@ -10,6 +11,7 @@ import {import {FILTER_OPERANDS_MAP,getFilterOperandsForFilterableFieldType,+ getFilterValueValidationIssue,isDefined,} from 'twenty-shared/utils';@@ -115,6 +117,18 @@ export class FlatViewFilterValidatorService {validationResult.errors.push(incompatibleOperandError);}+ const invalidValueError = this.getInvalidValueError({+ operand: flatViewFilterToValidate.operand,+ fieldType: referencedFieldMetadata.type,+ subFieldName: flatViewFilterToValidate.subFieldName,+ relationTargetFieldType,+ value: flatViewFilterToValidate.value,+ });++ if (isDefined(invalidValueError)) {+ validationResult.errors.push(invalidValueError);+ }+if (isFieldMetadataEntityOfType(referencedFieldMetadata,@@ -273,6 +287,26 @@ export class FlatViewFilterValidatorService {validationResult.errors.push(incompatibleOperandError);}+ if (+ 'value' in flatEntityUpdate ||+ 'fieldMetadataUniversalIdentifier' in flatEntityUpdate ||+ 'operand' in flatEntityUpdate ||+ 'subFieldName' in flatEntityUpdate ||+ 'relationTargetFieldMetadataUniversalIdentifier' in flatEntityUpdate+ ) {+ const invalidValueError = this.getInvalidValueError({+ operand: updatedFlatViewFilter.operand,+ fieldType: referencedFieldMetadata.type,+ subFieldName: updatedFlatViewFilter.subFieldName,+ relationTargetFieldType,+ value: updatedFlatViewFilter.value,+ });++ if (isDefined(invalidValueError)) {+ validationResult.errors.push(invalidValueError);+ }+ }+if (('value' in flatEntityUpdate ||'fieldMetadataUniversalIdentifier' in flatEntityUpdate ||@@ -353,22 +387,72 @@ export class FlatViewFilterValidatorService {};}- private getIncompatibleOperandError({+ private getInvalidValueError({operand,fieldType,subFieldName,relationTargetFieldType,+ value,}: {operand: ViewFilterOperand;fieldType: FieldMetadataType;subFieldName: string | null | undefined;relationTargetFieldType: FieldMetadataType | undefined;+ value: ViewFilterValue;}) {- const effectiveFieldType =- fieldType === FieldMetadataType.RELATION &&+ const issue = getFilterValueValidationIssue({+ fieldType: this.getEffectiveFieldType({+ fieldType,+ relationTargetFieldType,+ }),+ operand,+ subFieldName,+ value,+ });++ if (!isDefined(issue)) {+ return undefined;+ }++ const { stringifiedValue, filterType, hint } = issue;++ return {+ code: ViewFilterExceptionCode.INVALID_VIEW_FILTER_DATA,+ message: isNonEmptyString(hint)+ ? t`Value "${stringifiedValue}" is not valid for operand "${operand}" on field type "${filterType}". ${hint}`+ : t`Value "${stringifiedValue}" is not valid for operand "${operand}" on field type "${filterType}".`,+ userFriendlyMessage: msg`Filter value is not valid for this operand`,+ };+ }++ private getEffectiveFieldType({+ fieldType,+ relationTargetFieldType,+ }: {+ fieldType: FieldMetadataType;+ relationTargetFieldType: FieldMetadataType | undefined;+ }) {+ return fieldType === FieldMetadataType.RELATION &&isDefined(relationTargetFieldType)- ? relationTargetFieldType- : fieldType;+ ? relationTargetFieldType+ : fieldType;+ }++ private getIncompatibleOperandError({+ operand,+ fieldType,+ subFieldName,+ relationTargetFieldType,+ }: {+ operand: ViewFilterOperand;+ fieldType: FieldMetadataType;+ subFieldName: string | null | undefined;+ relationTargetFieldType: FieldMetadataType | undefined;+ }) {+ const effectiveFieldType = this.getEffectiveFieldType({+ fieldType,+ relationTargetFieldType,+ });if (!(effectiveFieldType in FILTER_OPERANDS_MAP)) {return undefined;diff --git a/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-sync-application-view-filter-value-validation.integration-spec.ts.snap b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-sync-application-view-filter-value-validation.integration-spec.ts.snapnew file mode 100644index 00000000000..8e68de7c690--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/__snapshots__/failing-sync-application-view-filter-value-validation.integration-spec.ts.snap@@ -0,0 +1,246 @@+// Jest Snapshot v1, https://goo.gl/fbAQLP++exports[`Sync application should fail on invalid view filter values when a BOOLEAN filter is neither true nor false 1`] = `+{+ "extensions": {+ "code": "METADATA_VALIDATION_FAILED",+ "errors": {+ "viewFilter": [+ {+ "errors": [+ {+ "code": "INVALID_VIEW_FILTER_DATA",+ "message": "Value "yes" is not valid for operand "IS" on field type "BOOLEAN". Invalid option: expected one of "true"|"false"",+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ ],+ "flatEntityMinimalInformation": {+ "universalIdentifier": Any<String>,+ },+ "metadataName": "viewFilter",+ "status": "fail",+ "type": "create",+ },+ ],+ },+ "message": "Validation failed for 1 viewFilter",+ "summary": {+ "totalErrors": 1,+ "viewFilter": 1,+ },+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ "message": "Validation errors occurred while syncing application manifest metadata",+ "name": "GraphQLError",+}+`;++exports[`Sync application should fail on invalid view filter values when a DATE filter is not an ISO date 1`] = `+{+ "extensions": {+ "code": "METADATA_VALIDATION_FAILED",+ "errors": {+ "viewFilter": [+ {+ "errors": [+ {+ "code": "INVALID_VIEW_FILTER_DATA",+ "message": "Value "31/01/2026" is not valid for operand "IS" on field type "DATE". Expected an ISO date, e.g. "2026-01-31"",+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ ],+ "flatEntityMinimalInformation": {+ "universalIdentifier": Any<String>,+ },+ "metadataName": "viewFilter",+ "status": "fail",+ "type": "create",+ },+ ],+ },+ "message": "Validation failed for 1 viewFilter",+ "summary": {+ "totalErrors": 1,+ "viewFilter": 1,+ },+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ "message": "Validation errors occurred while syncing application manifest metadata",+ "name": "GraphQLError",+}+`;++exports[`Sync application should fail on invalid view filter values when a NUMBER filter has trailing characters 1`] = `+{+ "extensions": {+ "code": "METADATA_VALIDATION_FAILED",+ "errors": {+ "viewFilter": [+ {+ "errors": [+ {+ "code": "INVALID_VIEW_FILTER_DATA",+ "message": "Value "30abc" is not valid for operand "IS" on field type "NUMBER". Expected a number",+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ ],+ "flatEntityMinimalInformation": {+ "universalIdentifier": Any<String>,+ },+ "metadataName": "viewFilter",+ "status": "fail",+ "type": "create",+ },+ ],+ },+ "message": "Validation failed for 1 viewFilter",+ "summary": {+ "totalErrors": 1,+ "viewFilter": 1,+ },+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ "message": "Validation errors occurred while syncing application manifest metadata",+ "name": "GraphQLError",+}+`;++exports[`Sync application should fail on invalid view filter values when a NUMBER filter is not a number 1`] = `+{+ "extensions": {+ "code": "METADATA_VALIDATION_FAILED",+ "errors": {+ "viewFilter": [+ {+ "errors": [+ {+ "code": "INVALID_VIEW_FILTER_DATA",+ "message": "Value "thirty" is not valid for operand "GREATER_THAN_OR_EQUAL" on field type "NUMBER". Expected a number",+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ ],+ "flatEntityMinimalInformation": {+ "universalIdentifier": Any<String>,+ },+ "metadataName": "viewFilter",+ "status": "fail",+ "type": "create",+ },+ ],+ },+ "message": "Validation failed for 1 viewFilter",+ "summary": {+ "totalErrors": 1,+ "viewFilter": 1,+ },+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ "message": "Validation errors occurred while syncing application manifest metadata",+ "name": "GraphQLError",+}+`;++exports[`Sync application should fail on invalid view filter values when a SELECT filter is an object rather than an array of options 1`] = `+{+ "extensions": {+ "code": "METADATA_VALIDATION_FAILED",+ "errors": {+ "viewFilter": [+ {+ "errors": [+ {+ "code": "INVALID_VIEW_FILTER_DATA",+ "message": "Value "{"stage":"WON"}" is not valid for operand "IS" on field type "SELECT". Expected an array of option values",+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ ],+ "flatEntityMinimalInformation": {+ "universalIdentifier": Any<String>,+ },+ "metadataName": "viewFilter",+ "status": "fail",+ "type": "create",+ },+ ],+ },+ "message": "Validation failed for 1 viewFilter",+ "summary": {+ "totalErrors": 1,+ "viewFilter": 1,+ },+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ "message": "Validation errors occurred while syncing application manifest metadata",+ "name": "GraphQLError",+}+`;++exports[`Sync application should fail on invalid view filter values when an IS_RELATIVE filter has no amount 1`] = `+{+ "extensions": {+ "code": "METADATA_VALIDATION_FAILED",+ "errors": {+ "viewFilter": [+ {+ "errors": [+ {+ "code": "INVALID_VIEW_FILTER_DATA",+ "message": "Value "NEXT__DAY" is not valid for operand "IS_RELATIVE" on field type "DATE". Expected a stringified relative date such as "NEXT_30_DAY".",+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ ],+ "flatEntityMinimalInformation": {+ "universalIdentifier": Any<String>,+ },+ "metadataName": "viewFilter",+ "status": "fail",+ "type": "create",+ },+ ],+ },+ "message": "Validation failed for 1 viewFilter",+ "summary": {+ "totalErrors": 1,+ "viewFilter": 1,+ },+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ "message": "Validation errors occurred while syncing application manifest metadata",+ "name": "GraphQLError",+}+`;++exports[`Sync application should fail on invalid view filter values when an IS_RELATIVE filter uses the relative date object form instead of its stringified form 1`] = `+{+ "extensions": {+ "code": "METADATA_VALIDATION_FAILED",+ "errors": {+ "viewFilter": [+ {+ "errors": [+ {+ "code": "INVALID_VIEW_FILTER_DATA",+ "message": "Value "{"direction":"NEXT","amount":30,"unit":"DAY"}" is not valid for operand "IS_RELATIVE" on field type "DATE". Expected a stringified relative date such as "NEXT_30_DAY".",+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ ],+ "flatEntityMinimalInformation": {+ "universalIdentifier": Any<String>,+ },+ "metadataName": "viewFilter",+ "status": "fail",+ "type": "create",+ },+ ],+ },+ "message": "Validation failed for 1 viewFilter",+ "summary": {+ "totalErrors": 1,+ "viewFilter": 1,+ },+ "userFriendlyMessage": "Filter value is not valid for this operand",+ },+ "message": "Validation errors occurred while syncing application manifest metadata",+ "name": "GraphQLError",+}+`;diff --git a/packages/twenty-server/test/integration/metadata/suites/application/failing-sync-application-view-filter-value-validation.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/failing-sync-application-view-filter-value-validation.integration-spec.tsnew file mode 100644index 00000000000..89642faeec2--- /dev/null+++ b/packages/twenty-server/test/integration/metadata/suites/application/failing-sync-application-view-filter-value-validation.integration-spec.ts@@ -0,0 +1,238 @@+import { expectOneNotInternalServerErrorSnapshot } from 'test/integration/graphql/utils/expect-one-not-internal-server-error-snapshot.util';+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';+import {+ type ObjectManifest,+ type ViewFilterManifest,+ type ViewManifest,+} from 'twenty-shared/application';+import {+ eachTestingContextFilter,+ type EachTestingContext,+} from 'twenty-shared/testing';+import {+ FieldMetadataType,+ ViewFilterOperand,+ ViewType,+} from 'twenty-shared/types';++const TEST_APP_ID = 'd1b2c3d4-0001-4000-a000-000000000001';+const TEST_ROLE_ID = 'd1b2c3d4-0002-4000-a000-000000000002';+const TEST_OBJECT_ID = 'd1b2c3d4-0003-4000-a000-000000000003';+const TEST_VIEW_ID = 'd1b2c3d4-0004-4000-a000-000000000004';+const TEST_VIEW_FILTER_ID = 'd1b2c3d4-0005-4000-a000-000000000005';++const NAME_FIELD_ID = 'd1b2c3d4-0100-4000-a000-000000000001';+const DATE_FIELD_ID = 'd1b2c3d4-0100-4000-a000-000000000002';+const NUMBER_FIELD_ID = 'd1b2c3d4-0100-4000-a000-000000000003';+const BOOLEAN_FIELD_ID = 'd1b2c3d4-0100-4000-a000-000000000004';+const SELECT_FIELD_ID = 'd1b2c3d4-0100-4000-a000-000000000005';++const SELECT_OPTION_ID = 'd1b2c3d4-0200-4000-a000-000000000001';++const buildObject = (): ObjectManifest => ({+ universalIdentifier: TEST_OBJECT_ID,+ nameSingular: 'filterValueSubject',+ namePlural: 'filterValueSubjects',+ labelSingular: 'Filter Value Subject',+ labelPlural: 'Filter Value Subjects',+ labelIdentifierFieldMetadataUniversalIdentifier: NAME_FIELD_ID,+ fields: [+ {+ universalIdentifier: NAME_FIELD_ID,+ name: 'name',+ label: 'Name',+ type: FieldMetadataType.TEXT,+ },+ {+ universalIdentifier: DATE_FIELD_ID,+ name: 'expiresAt',+ label: 'Expires At',+ type: FieldMetadataType.DATE,+ },+ {+ universalIdentifier: NUMBER_FIELD_ID,+ name: 'seatCount',+ label: 'Seat Count',+ type: FieldMetadataType.NUMBER,+ },+ {+ universalIdentifier: BOOLEAN_FIELD_ID,+ name: 'isActive',+ label: 'Is Active',+ type: FieldMetadataType.BOOLEAN,+ },+ {+ universalIdentifier: SELECT_FIELD_ID,+ name: 'stage',+ label: 'Stage',+ type: FieldMetadataType.SELECT,+ options: [+ {+ id: SELECT_OPTION_ID,+ label: 'Won',+ value: 'WON',+ position: 0,+ color: 'green',+ },+ ],+ },+ ],+});++const buildView = (viewFilter: ViewFilterManifest): ViewManifest => ({+ universalIdentifier: TEST_VIEW_ID,+ name: 'Filter Value View',+ objectUniversalIdentifier: TEST_OBJECT_ID,+ type: ViewType.TABLE,+ filters: [viewFilter],+});++type TestContext = {+ viewFilter: ViewFilterManifest;+};++const failingViewFilterValueSyncTestCases: EachTestingContext<TestContext>[] = [+ {+ title:+ 'when an IS_RELATIVE filter uses the relative date object form instead of its stringified form',+ context: {+ viewFilter: {+ universalIdentifier: TEST_VIEW_FILTER_ID,+ fieldMetadataUniversalIdentifier: DATE_FIELD_ID,+ operand: ViewFilterOperand.IS_RELATIVE,+ value: { direction: 'NEXT', amount: 30, unit: 'DAY' },+ },+ },+ },+ {+ title: 'when an IS_RELATIVE filter has no amount',+ context: {+ viewFilter: {+ universalIdentifier: TEST_VIEW_FILTER_ID,+ fieldMetadataUniversalIdentifier: DATE_FIELD_ID,+ operand: ViewFilterOperand.IS_RELATIVE,+ value: 'NEXT__DAY',+ },+ },+ },+ {+ title: 'when a DATE filter is not an ISO date',+ context: {+ viewFilter: {+ universalIdentifier: TEST_VIEW_FILTER_ID,+ fieldMetadataUniversalIdentifier: DATE_FIELD_ID,+ operand: ViewFilterOperand.IS,+ value: '31/01/2026',+ },+ },+ },+ {+ title: 'when a NUMBER filter is not a number',+ context: {+ viewFilter: {+ universalIdentifier: TEST_VIEW_FILTER_ID,+ fieldMetadataUniversalIdentifier: NUMBER_FIELD_ID,+ operand: ViewFilterOperand.GREATER_THAN_OR_EQUAL,+ value: 'thirty',+ },+ },+ },+ {+ title: 'when a NUMBER filter has trailing characters',+ context: {+ viewFilter: {+ universalIdentifier: TEST_VIEW_FILTER_ID,+ fieldMetadataUniversalIdentifier: NUMBER_FIELD_ID,+ operand: ViewFilterOperand.IS,+ value: '30abc',+ },+ },+ },+ {+ title: 'when a BOOLEAN filter is neither true nor false',+ context: {+ viewFilter: {+ universalIdentifier: TEST_VIEW_FILTER_ID,+ fieldMetadataUniversalIdentifier: BOOLEAN_FIELD_ID,+ operand: ViewFilterOperand.IS,+ value: 'yes',+ },+ },+ },+ {+ title: 'when a SELECT filter is an object rather than an array of options',+ context: {+ viewFilter: {+ universalIdentifier: TEST_VIEW_FILTER_ID,+ fieldMetadataUniversalIdentifier: SELECT_FIELD_ID,+ operand: ViewFilterOperand.IS,+ value: { stage: 'WON' },+ },+ },+ },+];++describe('Sync application should fail on invalid view filter values', () => {+ beforeAll(async () => {+ await setupApplicationForSync({+ applicationUniversalIdentifier: TEST_APP_ID,+ name: 'Test Invalid View Filter Value App',+ description: 'App for testing view filter value manifest validation',+ sourcePath: 'test-invalid-view-filter-value',+ });+ }, 60000);++ afterAll(async () => {+ await cleanupApplicationAndAppRegistration({+ applicationUniversalIdentifier: TEST_APP_ID,+ });+ });++ it.each(eachTestingContextFilter(failingViewFilterValueSyncTestCases))(+ '$title',+ async ({ context }) => {+ const { errors } = await syncApplication({+ manifest: buildBaseManifest({+ appId: TEST_APP_ID,+ roleId: TEST_ROLE_ID,+ overrides: {+ objects: [buildObject()],+ views: [buildView(context.viewFilter)],+ },+ }),+ expectToFail: true,+ });++ expectOneNotInternalServerErrorSnapshot({ errors });+ },+ 60000,+ );++ it('should sync the same view filters once their values are valid', async () => {+ const { errors } = await syncApplication({+ manifest: buildBaseManifest({+ appId: TEST_APP_ID,+ roleId: TEST_ROLE_ID,+ overrides: {+ objects: [buildObject()],+ views: [+ {+ ...buildView({+ universalIdentifier: TEST_VIEW_FILTER_ID,+ fieldMetadataUniversalIdentifier: DATE_FIELD_ID,+ operand: ViewFilterOperand.IS_RELATIVE,+ value: 'NEXT_30_DAY',+ }),+ },+ ],+ },+ }),+ expectToFail: false,+ });++ expect(errors).toBeUndefined();+ }, 60000);+});diff --git a/packages/twenty-server/test/integration/metadata/suites/view-filter/successful-view-filter-relation-traversal.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/view-filter/successful-view-filter-relation-traversal.integration-spec.tsindex b9381199533..a519a568ef7 100644--- a/packages/twenty-server/test/integration/metadata/suites/view-filter/successful-view-filter-relation-traversal.integration-spec.ts+++ b/packages/twenty-server/test/integration/metadata/suites/view-filter/successful-view-filter-relation-traversal.integration-spec.ts@@ -144,7 +144,7 @@ describe('View Filter relation-traversal round-trip should succeed', () => {viewId: createdViewId,fieldMetadataId: personCompanyRelationFieldId,operand: ViewFilterOperand.IS,- value: 'Acme',+ value: '["20202020-c02a-4a1b-b1a4-0f6b9b6b3b3b"]',},gqlFields: RELATION_TRAVERSAL_GQL_FIELDS,});diff --git a/packages/twenty-shared/src/utils/filter/dates/utils/relativeDateFilterStringifiedSchema.ts b/packages/twenty-shared/src/utils/filter/dates/utils/relativeDateFilterStringifiedSchema.tsindex 91b0c78b9ce..eae341efb01 100644--- a/packages/twenty-shared/src/utils/filter/dates/utils/relativeDateFilterStringifiedSchema.ts+++ b/packages/twenty-shared/src/utils/filter/dates/utils/relativeDateFilterStringifiedSchema.ts@@ -24,11 +24,21 @@ export const relativeDateFilterStringifiedSchema = zconst [_, direction, amount, unit, timezone, firstDayOfTheWeek] = result;- return relativeDateFilterSchema.parse({+ const parseResult = relativeDateFilterSchema.safeParse({direction,amount,unit,timezone,firstDayOfTheWeek,});++ if (!parseResult.success) {+ context.addIssue(+ `Cannot parse stringified inline relative date filter, value : "${value}"`,+ );++ return z.NEVER;+ }++ return parseResult.data;});diff --git a/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateFilter.ts b/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateFilter.tsindex 091d74b81f2..97ed5a1fc2b 100644--- a/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateFilter.ts+++ b/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateFilter.ts@@ -3,7 +3,7 @@ import { getNextPeriodStart } from '@/utils/filter/dates/utils/getNextPeriodStarimport { getPeriodStart } from '@/utils/filter/dates/utils/getPeriodStart';import { type RelativeDateFilter } from '@/utils/filter/dates/utils/relativeDateFilterSchema';import { subUnitFromZonedDateTime } from '@/utils/filter/dates/utils/subUnitFromZonedDateTime';-import { isDefined } from 'class-validator';+import { isDefined } from '@/utils/validation/isDefined';import { type Temporal } from 'temporal-polyfill';export const resolveRelativeDateFilter = (diff --git a/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateFilterStringified.ts b/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateFilterStringified.tsindex 030e3bb6516..e89ac2ceb1d 100644--- a/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateFilterStringified.ts+++ b/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateFilterStringified.ts@@ -1,7 +1,7 @@import { relativeDateFilterStringifiedSchema } from '@/utils/filter/dates/utils/relativeDateFilterStringifiedSchema';import { resolveRelativeDateFilter } from '@/utils/filter/dates/utils/resolveRelativeDateFilter';import { isNonEmptyString } from '@sniptt/guards';-import { isDefined } from 'class-validator';+import { isDefined } from '@/utils/validation/isDefined';import { Temporal } from 'temporal-polyfill';export const resolveRelativeDateFilterStringified = (diff --git a/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateTimeFilterStringified.ts b/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateTimeFilterStringified.tsindex c83b465df16..b0d3dfa7043 100644--- a/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateTimeFilterStringified.ts+++ b/packages/twenty-shared/src/utils/filter/dates/utils/resolveRelativeDateTimeFilterStringified.ts@@ -1,7 +1,7 @@import { relativeDateFilterStringifiedSchema } from '@/utils/filter/dates/utils/relativeDateFilterStringifiedSchema';import { resolveRelativeDateTimeFilter } from '@/utils/filter/dates/utils/resolveRelativeDateTimeFilter';import { isNonEmptyString } from '@sniptt/guards';-import { isDefined } from 'class-validator';+import { isDefined } from '@/utils/validation/isDefined';import { Temporal } from 'temporal-polyfill';export const resolveRelativeDateTimeFilterStringified = (diff --git a/packages/twenty-shared/src/utils/filter/index.ts b/packages/twenty-shared/src/utils/filter/index.tsindex b94e495830b..c058b207fd0 100644--- a/packages/twenty-shared/src/utils/filter/index.ts+++ b/packages/twenty-shared/src/utils/filter/index.ts@@ -37,3 +37,7 @@ export * from './utils/isMatchingUUIDFilter';export * from './utils/validation-schemas/arrayOfStringsOrVariablesSchema';export * from './utils/validation-schemas/arrayOfUuidsOrVariablesSchema';export * from './utils/validation-schemas/jsonRelationFilterValueSchema';+export * from './utils/validation-schemas/filterValueScalarSchemas';+export * from './utils/validation-schemas/filterValueSchemasMap';+export * from './utils/validation-schemas/getFilterValueSchema';+export * from './utils/validation-schemas/getFilterValueValidationIssue';diff --git a/packages/twenty-shared/src/utils/filter/turnRecordFilterIntoGqlOperationFilter.ts b/packages/twenty-shared/src/utils/filter/turnRecordFilterIntoGqlOperationFilter.tsindex 812882af45d..b39d7bd87a2 100644--- a/packages/twenty-shared/src/utils/filter/turnRecordFilterIntoGqlOperationFilter.ts+++ b/packages/twenty-shared/src/utils/filter/turnRecordFilterIntoGqlOperationFilter.ts@@ -53,6 +53,13 @@ import {type RecordFilter,} from '@/utils';import { arrayOfStringsOrVariablesSchema } from '@/utils/filter/utils/validation-schemas/arrayOfStringsOrVariablesSchema';+import {+ actorSourceFilterValueSchema,+ booleanFilterValueSchema,+ instantFilterValueSchema,+ numericFilterValueSchema,+ plainDateOrInstantFilterValueSchema,+} from '@/utils/filter/utils/validation-schemas/filterValueScalarSchemas';import { arrayOfUuidOrVariableSchema } from '@/utils/filter/utils/validation-schemas/arrayOfUuidsOrVariablesSchema';import { jsonRelationFilterValueSchema } from '@/utils/filter/utils/validation-schemas/jsonRelationFilterValueSchema';import {@@ -64,6 +71,20 @@ const PHONE_FILTER_NON_SIGNIFICANT_CHARS = /(?!^)\+|[^0-9+]/g;const CONTAINS_DIGIT = /[0-9]/;+const lenientBooleanFilterValueSchema = booleanFilterValueSchema.catch(false);++const parseNumericFilterValue = (value: string): number => {+ const parsed = numericFilterValueSchema.safeParse(value);++ return parsed.success ? parsed.data : parseFloat(value);+};++const parseActorSourceFilterValue = (value: string): string[] => {+ const parsed = actorSourceFilterValueSchema.safeParse(value);++ return parsed.success ? parsed.data : (JSON.parse(value) as string[]);+};+type FieldSharedMorphRelation = {type: RelationType;targetObjectMetadata: {@@ -492,20 +513,21 @@ const buildDirectFieldGqlOperationFilter = ({if (recordFilter.operand === RecordFilterOperand.IS) {const timeZone = filterValueDependencies.timeZone ?? 'UTC';- let parsedPlainDate = null;+ const parsedDateTime = plainDateOrInstantFilterValueSchema.safeParse(+ recordFilter.value,+ );- try {- parsedPlainDate = recordFilter.value.includes('T')- ? Temporal.Instant.from(recordFilter.value)- .toZonedDateTimeISO(timeZone)- .toPlainDate()- : Temporal.PlainDate.from(recordFilter.value);- } catch {+ if (!parsedDateTime.success) {throw new Error(`Cannot parse "${recordFilter.value}" for ${filterType} filter`,);}+ const parsedPlainDate =+ parsedDateTime.data instanceof Temporal.Instant+ ? parsedDateTime.data.toZonedDateTimeISO(timeZone).toPlainDate()+ : parsedDateTime.data;+const zonedDateTime = parsedPlainDate.toZonedDateTime(timeZone);const start = zonedDateTime.toInstant();const end = zonedDateTime.add({ days: 1 }).toInstant();@@ -526,7 +548,9 @@ const buildDirectFieldGqlOperationFilter = ({};}- const resolvedDateTime = Temporal.Instant.from(recordFilter.value);+ const resolvedDateTime = instantFilterValueSchema.parse(+ recordFilter.value,+ );switch (recordFilter.operand) {case RecordFilterOperand.IS_AFTER: {@@ -555,14 +579,18 @@ const buildDirectFieldGqlOperationFilter = ({case RecordFilterOperand.IS:return {[fieldMetadataItem.name]: {- eq: convertRatingToRatingValue(parseFloat(recordFilter.value)),+ eq: convertRatingToRatingValue(+ parseNumericFilterValue(recordFilter.value),+ ),} as RatingFilter,};case RecordFilterOperand.IS_NOT:return {not: {[fieldMetadataItem.name]: {- eq: convertRatingToRatingValue(parseFloat(recordFilter.value)),+ eq: convertRatingToRatingValue(+ parseNumericFilterValue(recordFilter.value),+ ),} as RatingFilter,},};@@ -570,7 +598,7 @@ const buildDirectFieldGqlOperationFilter = ({return {[fieldMetadataItem.name]: {in: convertGreaterThanOrEqualRatingToArrayOfRatingValues(- parseFloat(recordFilter.value),+ parseNumericFilterValue(recordFilter.value),),} as RatingFilter,};@@ -578,7 +606,7 @@ const buildDirectFieldGqlOperationFilter = ({return {[fieldMetadataItem.name]: {in: convertLessThanOrEqualRatingToArrayOfRatingValues(- parseFloat(recordFilter.value),+ parseNumericFilterValue(recordFilter.value),),} as RatingFilter,};@@ -592,26 +620,26 @@ const buildDirectFieldGqlOperationFilter = ({case RecordFilterOperand.GREATER_THAN_OR_EQUAL:return {[fieldMetadataItem.name]: {- gte: parseFloat(recordFilter.value),+ gte: parseNumericFilterValue(recordFilter.value),} as FloatFilter,};case RecordFilterOperand.LESS_THAN_OR_EQUAL:return {[fieldMetadataItem.name]: {- lte: parseFloat(recordFilter.value),+ lte: parseNumericFilterValue(recordFilter.value),} as FloatFilter,};case RecordFilterOperand.IS:return {[fieldMetadataItem.name]: {- eq: parseFloat(recordFilter.value),+ eq: parseNumericFilterValue(recordFilter.value),} as FloatFilter,};case RecordFilterOperand.IS_NOT:return {not: {[fieldMetadataItem.name]: {- eq: parseFloat(recordFilter.value),+ eq: parseNumericFilterValue(recordFilter.value),} as FloatFilter,},};@@ -732,19 +760,25 @@ const buildDirectFieldGqlOperationFilter = ({case RecordFilterOperand.GREATER_THAN_OR_EQUAL:return {[fieldMetadataItem.name]: {- amountMicros: { gte: parseFloat(recordFilter.value) * 1000000 },+ amountMicros: {+ gte: parseNumericFilterValue(recordFilter.value) * 1000000,+ },} as CurrencyFilter,};case RecordFilterOperand.LESS_THAN_OR_EQUAL:return {[fieldMetadataItem.name]: {- amountMicros: { lte: parseFloat(recordFilter.value) * 1000000 },+ amountMicros: {+ lte: parseNumericFilterValue(recordFilter.value) * 1000000,+ },} as CurrencyFilter,};case RecordFilterOperand.IS:return {[fieldMetadataItem.name]: {- amountMicros: { eq: parseFloat(recordFilter.value) * 1000000 },+ amountMicros: {+ eq: parseNumericFilterValue(recordFilter.value) * 1000000,+ },} as CurrencyFilter,};case RecordFilterOperand.IS_NOT:@@ -752,7 +786,7 @@ const buildDirectFieldGqlOperationFilter = ({not: {[fieldMetadataItem.name]: {amountMicros: {- eq: parseFloat(recordFilter.value) * 1000000,+ eq: parseNumericFilterValue(recordFilter.value) * 1000000,},} as CurrencyFilter,},@@ -1027,9 +1061,9 @@ const buildDirectFieldGqlOperationFilter = ({};} else {if (subFieldName === 'addressCountry') {- const parsedCountryCodes = JSON.parse(+ const parsedCountryCodes = arrayOfStringsOrVariablesSchema.parse(recordFilter.value,- ) as string[];+ );if (recordFilter.value === '[]' ||@@ -1044,7 +1078,7 @@ const buildDirectFieldGqlOperationFilter = ({not: {[fieldMetadataItem.name]: {addressCountry: {- in: JSON.parse(recordFilter.value),+ in: parsedCountryCodes,} as AddressFilter,},},@@ -1235,7 +1269,9 @@ const buildDirectFieldGqlOperationFilter = ({return;}- const parsedSources = JSON.parse(recordFilter.value) as string[];+ const parsedSources = parseActorSourceFilterValue(+ recordFilter.value,+ );return {[fieldMetadataItem.name]: {@@ -1250,7 +1286,9 @@ const buildDirectFieldGqlOperationFilter = ({return;}- const parsedSources = JSON.parse(recordFilter.value) as string[];+ const parsedSources = parseActorSourceFilterValue(+ recordFilter.value,+ );if (parsedSources.length === 0) return;@@ -1597,7 +1635,7 @@ const buildDirectFieldGqlOperationFilter = ({case 'BOOLEAN': {return {[fieldMetadataItem.name]: {- eq: recordFilter.value === 'true',+ eq: lenientBooleanFilterValueSchema.parse(recordFilter.value),} as BooleanFilter,};}diff --git a/packages/twenty-shared/src/utils/filter/utils/__tests__/getFilterValueSchema.test.ts b/packages/twenty-shared/src/utils/filter/utils/__tests__/getFilterValueSchema.test.tsnew file mode 100644index 00000000000..de11a73893c--- /dev/null+++ b/packages/twenty-shared/src/utils/filter/utils/__tests__/getFilterValueSchema.test.ts@@ -0,0 +1,327 @@+import {+ type FilterableAndTSVectorFieldType,+ ViewFilterOperand,+} from '@/types';+import { getFilterValueSchema } from '@/utils/filter/utils/validation-schemas/getFilterValueSchema';++const ISSUE_23397_VALUE = '{"unit":"DAY","amount":30,"direction":"NEXT"}';++const expectAccepted = (+ args: {+ filterType: FilterableAndTSVectorFieldType;+ operand: ViewFilterOperand;+ subFieldName?: string;+ },+ value: string,+) => {+ const schema = getFilterValueSchema(args);++ expect(schema?.safeParse(value).success).toBe(true);+};++const expectRejected = (+ args: {+ filterType: FilterableAndTSVectorFieldType;+ operand: ViewFilterOperand;+ subFieldName?: string;+ },+ value: string,+) => {+ const schema = getFilterValueSchema(args);++ expect(schema?.safeParse(value).success).toBe(false);+};++describe('getFilterValueSchema', () => {+ it('should return no schema for operands not expecting a value', () => {+ expect(+ getFilterValueSchema({+ filterType: 'DATE',+ operand: ViewFilterOperand.IS_EMPTY,+ }),+ ).toBeUndefined();++ expect(+ getFilterValueSchema({+ filterType: 'DATE',+ operand: ViewFilterOperand.IS_TODAY,+ }),+ ).toBeUndefined();+ });++ describe('IS_RELATIVE', () => {+ it.each(['NEXT__DAY', 'NEXT_0_DAY'])(+ 'should reject %s without throwing',+ (value) => {+ expectRejected(+ { filterType: 'DATE', operand: ViewFilterOperand.IS_RELATIVE },+ value,+ );+ },+ );++ it.each(['DATE', 'DATE_TIME'] as const)(+ 'should accept a stringified relative date on %s',+ (filterType) => {+ expectAccepted(+ { filterType, operand: ViewFilterOperand.IS_RELATIVE },+ 'NEXT_30_DAY',+ );+ },+ );++ it.each(['DATE', 'DATE_TIME'] as const)(+ 'should reject the object form of a relative date on %s',+ (filterType) => {+ expectRejected(+ { filterType, operand: ViewFilterOperand.IS_RELATIVE },+ ISSUE_23397_VALUE,+ );+ },+ );++ it('should accept the timezone and first day of week suffix the UI emits', () => {+ expectAccepted(+ { filterType: 'DATE', operand: ViewFilterOperand.IS_RELATIVE },+ 'NEXT_30_DAY;;Europe/Paris;;MONDAY;;',+ );+ });+ });++ describe('dates', () => {+ it('should accept a plain date on DATE', () => {+ expectAccepted(+ { filterType: 'DATE', operand: ViewFilterOperand.IS },+ '2026-01-31',+ );+ });++ it('should reject a non date on DATE', () => {+ expectRejected(+ { filterType: 'DATE', operand: ViewFilterOperand.IS },+ ISSUE_23397_VALUE,+ );+ });++ it.each(['2026-01-31', '2026-01-31T10:00:00Z'])(+ 'should accept %s on DATE_TIME IS',+ (value) => {+ expectAccepted(+ { filterType: 'DATE_TIME', operand: ViewFilterOperand.IS },+ value,+ );+ },+ );++ it('should reject a plain date on DATE_TIME IS_AFTER', () => {+ expectRejected(+ { filterType: 'DATE_TIME', operand: ViewFilterOperand.IS_AFTER },+ '2026-01-31',+ );+ });+ });++ describe('numbers', () => {+ it.each(['NUMBER', 'RATING', 'CURRENCY'] as const)(+ 'should accept a numeric string on %s',+ (filterType) => {+ expectAccepted(+ { filterType, operand: ViewFilterOperand.GREATER_THAN_OR_EQUAL },+ '30',+ );+ },+ );++ it('should reject a non numeric string on NUMBER', () => {+ expectRejected(+ { filterType: 'NUMBER', operand: ViewFilterOperand.IS },+ ISSUE_23397_VALUE,+ );+ });+ });++ describe('select', () => {+ it('should accept a stringified array of options', () => {+ expectAccepted(+ { filterType: 'SELECT', operand: ViewFilterOperand.IS },+ '["WON","LOST"]',+ );+ });++ it.each(['OPTION_0', '{bad json'])(+ 'should accept %s as a legacy scalar option value',+ (value) => {+ expectAccepted(+ { filterType: 'SELECT', operand: ViewFilterOperand.IS },+ value,+ );+ },+ );++ it('should reject an object rather than an array', () => {+ expectRejected(+ { filterType: 'SELECT', operand: ViewFilterOperand.IS },+ ISSUE_23397_VALUE,+ );+ });++ it('should reject a json array that is not an array of strings', () => {+ expectRejected(+ { filterType: 'MULTI_SELECT', operand: ViewFilterOperand.CONTAINS },+ '[1, 2]',+ );+ });+ });++ describe('relation', () => {+ it('should accept the relation filter object form', () => {+ expectAccepted(+ { filterType: 'RELATION', operand: ViewFilterOperand.IS },+ '{"selectedRecordIds":["20202020-1c25-4d02-bf25-6aeccf7ea419"]}',+ );+ });++ it('should accept a bare array of uuids', () => {+ expectAccepted(+ { filterType: 'RELATION', operand: ViewFilterOperand.IS },+ '["20202020-1c25-4d02-bf25-6aeccf7ea419"]',+ );+ });++ it('should reject a value that resolves to no record id', () => {+ expectRejected(+ { filterType: 'RELATION', operand: ViewFilterOperand.IS },+ ISSUE_23397_VALUE,+ );+ });+ });++ describe('uuid', () => {+ it('should reject a non uuid instead of silently matching nothing', () => {+ expectRejected(+ { filterType: 'UUID', operand: ViewFilterOperand.IS },+ ISSUE_23397_VALUE,+ );+ });+ });++ describe('boolean', () => {+ it.each(['true', 'false'])('should accept %s', (value) => {+ expectAccepted(+ { filterType: 'BOOLEAN', operand: ViewFilterOperand.IS },+ value,+ );+ });++ it('should reject anything else', () => {+ expectRejected(+ { filterType: 'BOOLEAN', operand: ViewFilterOperand.IS },+ ISSUE_23397_VALUE,+ );+ });+ });++ describe('composite sub fields', () => {+ it('should validate currencyCode as an array of codes', () => {+ expectAccepted(+ {+ filterType: 'CURRENCY',+ operand: ViewFilterOperand.IS,+ subFieldName: 'currencyCode',+ },+ '["EUR"]',+ );++ expectRejected(+ {+ filterType: 'CURRENCY',+ operand: ViewFilterOperand.IS,+ subFieldName: 'currencyCode',+ },+ 'EUR',+ );+ });++ it('should validate the actor source against known sources', () => {+ expectAccepted(+ {+ filterType: 'ACTOR',+ operand: ViewFilterOperand.IS,+ subFieldName: 'source',+ },+ '["MANUAL","API"]',+ );++ expectRejected(+ {+ filterType: 'ACTOR',+ operand: ViewFilterOperand.IS,+ subFieldName: 'source',+ },+ '["NOT_A_SOURCE"]',+ );+ });++ it('should validate actor workspaceMemberId as a relation value', () => {+ expectAccepted(+ {+ filterType: 'ACTOR',+ operand: ViewFilterOperand.IS,+ subFieldName: 'workspaceMemberId',+ },+ '{"selectedRecordIds":["20202020-1c25-4d02-bf25-6aeccf7ea419"]}',+ );+ });++ it('should validate addressCountry as an array of codes', () => {+ expectAccepted(+ {+ filterType: 'ADDRESS',+ operand: ViewFilterOperand.CONTAINS,+ subFieldName: 'addressCountry',+ },+ '["FR"]',+ );++ expectRejected(+ {+ filterType: 'ADDRESS',+ operand: ViewFilterOperand.CONTAINS,+ subFieldName: 'addressCountry',+ },+ 'FR',+ );+ });++ it('should keep the text contract on other address sub fields', () => {+ expectAccepted(+ {+ filterType: 'ADDRESS',+ operand: ViewFilterOperand.CONTAINS,+ subFieldName: 'addressStreet1',+ },+ 'rue de Rivoli',+ );+ });++ it('should fall back to the text contract on other actor sub fields', () => {+ expectAccepted(+ {+ filterType: 'ACTOR',+ operand: ViewFilterOperand.CONTAINS,+ subFieldName: 'name',+ },+ 'Alice',+ );+ });+ });++ describe('text', () => {+ it('should reject an empty value', () => {+ expectRejected(+ { filterType: 'TEXT', operand: ViewFilterOperand.CONTAINS },+ '',+ );+ });+ });+});diff --git a/packages/twenty-shared/src/utils/filter/utils/validation-schemas/arrayOfStringsOrVariablesSchema.ts b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/arrayOfStringsOrVariablesSchema.tsindex 17690b44766..7fe54faf893 100644--- a/packages/twenty-shared/src/utils/filter/utils/validation-schemas/arrayOfStringsOrVariablesSchema.ts+++ b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/arrayOfStringsOrVariablesSchema.ts@@ -1,14 +1,22 @@-import { isValidVariable } from '@/utils';+import { isValidVariable } from '@/utils/validation/isValidVariable';import { z } from 'zod';export const arrayOfStringsOrVariablesSchema = z.string()- .transform((val) => {+ .transform((val, ctx) => {if (val === '') return [];if (isValidVariable(val) as boolean) {return [val];}- return JSON.parse(val);+ try {+ return JSON.parse(val);+ } catch (error) {+ ctx.addIssue({+ code: 'custom',+ message: (error as Error).message,+ });+ return z.NEVER;+ }}).refine((parsed) =>diff --git a/packages/twenty-shared/src/utils/filter/utils/validation-schemas/arrayOfUuidsOrVariablesSchema.ts b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/arrayOfUuidsOrVariablesSchema.tsindex 16c6128d423..2a97dcac27e 100644--- a/packages/twenty-shared/src/utils/filter/utils/validation-schemas/arrayOfUuidsOrVariablesSchema.ts+++ b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/arrayOfUuidsOrVariablesSchema.ts@@ -1,30 +1,32 @@-import { isValidUuid, isValidVariable } from '@/utils';+import { isValidUuid } from '@/utils/validation/isValidUuid';+import { isValidVariable } from '@/utils/validation/isValidVariable';import { z } from 'zod';-export const arrayOfUuidOrVariableSchema = z- .preprocess(- (value) => {- try {- if (typeof value === 'string') {- if (isValidVariable(value) as boolean) {- return [value];- }- try {- const parsed = JSON.parse(value);- return Array.isArray(parsed) ? parsed : [parsed];- } catch {- return [value];- }+export const strictArrayOfUuidOrVariableSchema = z.preprocess(+ (value) => {+ try {+ if (typeof value === 'string') {+ if (isValidVariable(value) as boolean) {+ return [value];+ }+ try {+ const parsed = JSON.parse(value);+ return Array.isArray(parsed) ? parsed : [parsed];+ } catch {+ return [value];}- return Array.isArray(value) ? value : [value];- } catch {- return [];}- },- z.array(- z.string().refine((val) => {- return isValidUuid(val) || isValidVariable(val);- }, 'Must be a valid UUID or a variable with {{ }} syntax'),- ),- )- .catch([]);+ return Array.isArray(value) ? value : [value];+ } catch {+ return [];+ }+ },+ z.array(+ z.string().refine((val) => {+ return isValidUuid(val) || isValidVariable(val);+ }, 'Must be a valid UUID or a variable with {{ }} syntax'),+ ),+);++export const arrayOfUuidOrVariableSchema =+ strictArrayOfUuidOrVariableSchema.catch([]);diff --git a/packages/twenty-shared/src/utils/filter/utils/validation-schemas/filterValueScalarSchemas.ts b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/filterValueScalarSchemas.tsnew file mode 100644index 00000000000..bf402f6ef15--- /dev/null+++ b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/filterValueScalarSchemas.ts@@ -0,0 +1,66 @@+import { Temporal } from 'temporal-polyfill';+import { z } from 'zod';++import { FieldActorSource } from '@/types';++export const nonEmptyStringFilterValueSchema = z.string().min(1);++const NUMERIC_VALUE = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;++export const numericFilterValueSchema = z+ .string()+ .refine((value) => NUMERIC_VALUE.test(value.trim()), 'Expected a number')+ .transform((value) => parseFloat(value))+ .refine((value) => Number.isFinite(value), 'Expected a finite number');++const temporalSchema = <TParsed>(+ parse: (value: string) => TParsed,+ message: string,+) =>+ z.string().transform((value, ctx) => {+ try {+ return parse(value);+ } catch {+ ctx.addIssue({ code: 'custom', message });++ return z.NEVER;+ }+ });++export const plainDateFilterValueSchema = temporalSchema(+ (value) => Temporal.PlainDate.from(value),+ 'Expected an ISO date, e.g. "2026-01-31"',+);++export const instantFilterValueSchema = temporalSchema(+ (value) => Temporal.Instant.from(value),+ 'Expected an ISO date time, e.g. "2026-01-31T00:00:00Z"',+);++export const plainDateOrInstantFilterValueSchema = temporalSchema(+ (value) =>+ value.includes('T')+ ? Temporal.Instant.from(value)+ : Temporal.PlainDate.from(value),+ 'Expected an ISO date or date time',+);++export const booleanFilterValueSchema = z+ .enum(['true', 'false'])+ .transform((value) => value === 'true');++export const actorSourceFilterValueSchema = z+ .string()+ .transform((value, ctx) => {+ try {+ return JSON.parse(value);+ } catch (error) {+ ctx.addIssue({+ code: 'custom',+ message: (error as Error).message,+ });++ return z.NEVER;+ }+ })+ .pipe(z.array(z.enum(FieldActorSource)));diff --git a/packages/twenty-shared/src/utils/filter/utils/validation-schemas/filterValueSchemasMap.ts b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/filterValueSchemasMap.tsnew file mode 100644index 00000000000..d707d9c7e64--- /dev/null+++ b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/filterValueSchemasMap.ts@@ -0,0 +1,159 @@+import { type z } from 'zod';++import { ViewFilterOperand } from '@/types';+import { relativeDateFilterStringifiedSchema } from '@/utils/filter/dates/utils/relativeDateFilterStringifiedSchema';+import { arrayOfStringsOrVariablesSchema } from '@/utils/filter/utils/validation-schemas/arrayOfStringsOrVariablesSchema';+import { strictArrayOfUuidOrVariableSchema } from '@/utils/filter/utils/validation-schemas/arrayOfUuidsOrVariablesSchema';+import {+ actorSourceFilterValueSchema,+ booleanFilterValueSchema,+ instantFilterValueSchema,+ nonEmptyStringFilterValueSchema,+ numericFilterValueSchema,+ plainDateFilterValueSchema,+ plainDateOrInstantFilterValueSchema,+} from '@/utils/filter/utils/validation-schemas/filterValueScalarSchemas';+import { jsonRelationFilterValueSchema } from '@/utils/filter/utils/validation-schemas/jsonRelationFilterValueSchema';+import { type FILTER_OPERANDS_MAP } from '@/utils/filter/utils/filterOperandsMap';++type ValuelessOperand =+ | ViewFilterOperand.IS_NOT_NULL+ | ViewFilterOperand.IS_EMPTY+ | ViewFilterOperand.IS_NOT_EMPTY+ | ViewFilterOperand.IS_IN_PAST+ | ViewFilterOperand.IS_IN_FUTURE+ | ViewFilterOperand.IS_TODAY;++type FilterValueSchemasMap = {+ [FilterType in keyof typeof FILTER_OPERANDS_MAP]: Record<+ Exclude<(typeof FILTER_OPERANDS_MAP)[FilterType][number], ValuelessOperand>,+ z.ZodType+ > &+ Partial<Record<ViewFilterOperand, z.ZodType>>;+};++const relationFilterValueSchema = jsonRelationFilterValueSchema+ .refine(+ ({ selectedRecordIds }) =>+ strictArrayOfUuidOrVariableSchema.safeParse(selectedRecordIds).success,+ 'Expected selectedRecordIds to contain UUIDs or variables',+ )+ .or(strictArrayOfUuidOrVariableSchema);++// Mirrors normalizeSelectFilterValues: a value that is not JSON is a legacy scalar option.+const selectFilterValueSchema = nonEmptyStringFilterValueSchema.refine(+ (value) => {+ if (arrayOfStringsOrVariablesSchema.safeParse(value).success) {+ return true;+ }++ try {+ JSON.parse(value);+ } catch {+ return true;+ }++ return false;+ },+ 'Expected an array of option values',+);++const containsOperandsSchemas = {+ [ViewFilterOperand.CONTAINS]: nonEmptyStringFilterValueSchema,+ [ViewFilterOperand.DOES_NOT_CONTAIN]: nonEmptyStringFilterValueSchema,+};++const numericOperandsSchemas = {+ [ViewFilterOperand.IS]: numericFilterValueSchema,+ [ViewFilterOperand.IS_NOT]: numericFilterValueSchema,+ [ViewFilterOperand.GREATER_THAN_OR_EQUAL]: numericFilterValueSchema,+ [ViewFilterOperand.LESS_THAN_OR_EQUAL]: numericFilterValueSchema,+};++export const FILTER_VALUE_SCHEMAS_MAP = {+ TEXT: containsOperandsSchemas,+ EMAILS: containsOperandsSchemas,+ FULL_NAME: containsOperandsSchemas,+ ADDRESS: containsOperandsSchemas,+ LINKS: containsOperandsSchemas,+ PHONES: containsOperandsSchemas,+ RAW_JSON: containsOperandsSchemas,+ FILES: containsOperandsSchemas,+ ARRAY: containsOperandsSchemas,+ ACTOR: containsOperandsSchemas,+ MULTI_SELECT: {+ [ViewFilterOperand.CONTAINS]: selectFilterValueSchema,+ [ViewFilterOperand.DOES_NOT_CONTAIN]: selectFilterValueSchema,+ },+ SELECT: {+ [ViewFilterOperand.IS]: selectFilterValueSchema,+ [ViewFilterOperand.IS_NOT]: selectFilterValueSchema,+ },+ CURRENCY: numericOperandsSchemas,+ NUMBER: numericOperandsSchemas,+ RATING: numericOperandsSchemas,+ DATE: {+ [ViewFilterOperand.IS]: plainDateFilterValueSchema,+ [ViewFilterOperand.IS_BEFORE]: plainDateFilterValueSchema,+ [ViewFilterOperand.IS_AFTER]: plainDateFilterValueSchema,+ [ViewFilterOperand.IS_RELATIVE]: relativeDateFilterStringifiedSchema,+ },+ DATE_TIME: {+ [ViewFilterOperand.IS]: plainDateOrInstantFilterValueSchema,+ [ViewFilterOperand.IS_BEFORE]: instantFilterValueSchema,+ [ViewFilterOperand.IS_AFTER]: instantFilterValueSchema,+ [ViewFilterOperand.IS_RELATIVE]: relativeDateFilterStringifiedSchema,+ },+ RELATION: {+ [ViewFilterOperand.IS]: relationFilterValueSchema,+ [ViewFilterOperand.IS_NOT]: relationFilterValueSchema,+ },+ UUID: {+ [ViewFilterOperand.IS]: strictArrayOfUuidOrVariableSchema,+ [ViewFilterOperand.IS_NOT]: strictArrayOfUuidOrVariableSchema,+ },+ BOOLEAN: {+ [ViewFilterOperand.IS]: booleanFilterValueSchema,+ },+ TS_VECTOR: {+ [ViewFilterOperand.VECTOR_SEARCH]: nonEmptyStringFilterValueSchema,+ },+} as const satisfies FilterValueSchemasMap;++export const COMPOSITE_SUB_FIELD_VALUE_SCHEMAS = {+ ACTOR: {+ source: {+ [ViewFilterOperand.IS]: actorSourceFilterValueSchema,+ [ViewFilterOperand.IS_NOT]: actorSourceFilterValueSchema,+ },+ workspaceMemberId: {+ [ViewFilterOperand.IS]: relationFilterValueSchema,+ [ViewFilterOperand.IS_NOT]: relationFilterValueSchema,+ },+ },+ CURRENCY: {+ currencyCode: {+ [ViewFilterOperand.IS]: arrayOfStringsOrVariablesSchema,+ [ViewFilterOperand.IS_NOT]: arrayOfStringsOrVariablesSchema,+ },+ },+ ADDRESS: {+ addressCountry: {+ [ViewFilterOperand.CONTAINS]: arrayOfStringsOrVariablesSchema,+ [ViewFilterOperand.DOES_NOT_CONTAIN]: arrayOfStringsOrVariablesSchema,+ },+ },+} as const satisfies Partial<+ Record<+ keyof typeof FILTER_OPERANDS_MAP,+ Record<string, Partial<Record<ViewFilterOperand, z.ZodType>>>+ >+>;++export const FILTER_VALUE_FORMAT_HINTS: Partial<+ Record<ViewFilterOperand, string>+> = {+ [ViewFilterOperand.IS_RELATIVE]:+ 'Expected a stringified relative date such as "NEXT_30_DAY".',+ [ViewFilterOperand.VECTOR_SEARCH]: 'Expected a non empty search string.',+};diff --git a/packages/twenty-shared/src/utils/filter/utils/validation-schemas/getFilterValueSchema.ts b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/getFilterValueSchema.tsnew file mode 100644index 00000000000..89de8cdfa3f--- /dev/null+++ b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/getFilterValueSchema.ts@@ -0,0 +1,39 @@+import { type z } from 'zod';++import {+ type FilterableAndTSVectorFieldType,+ type ViewFilterOperand,+} from '@/types';+import { isRecordFilterOperandExpectingValue } from '@/utils/filter/isRecordFilterOperandExpectingValue';+import { isDefined } from '@/utils/validation/isDefined';+import {+ COMPOSITE_SUB_FIELD_VALUE_SCHEMAS,+ FILTER_VALUE_SCHEMAS_MAP,+} from '@/utils/filter/utils/validation-schemas/filterValueSchemasMap';++type OperandSchemas = Partial<Record<ViewFilterOperand, z.ZodType>>;++export const getFilterValueSchema = ({+ filterType,+ operand,+ subFieldName,+}: {+ filterType: FilterableAndTSVectorFieldType;+ operand: ViewFilterOperand;+ subFieldName?: string | null | undefined;+}): z.ZodType | undefined => {+ if (!isRecordFilterOperandExpectingValue(operand)) {+ return undefined;+ }++ const subFieldSchemas: Record<string, OperandSchemas> | undefined =+ COMPOSITE_SUB_FIELD_VALUE_SCHEMAS[+ filterType as keyof typeof COMPOSITE_SUB_FIELD_VALUE_SCHEMAS+ ];++ if (isDefined(subFieldName) && isDefined(subFieldSchemas?.[subFieldName])) {+ return subFieldSchemas[subFieldName][operand];+ }++ return (FILTER_VALUE_SCHEMAS_MAP[filterType] as OperandSchemas)[operand];+};diff --git a/packages/twenty-shared/src/utils/filter/utils/validation-schemas/getFilterValueValidationIssue.ts b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/getFilterValueValidationIssue.tsnew file mode 100644index 00000000000..6e944f2eb7c--- /dev/null+++ b/packages/twenty-shared/src/utils/filter/utils/validation-schemas/getFilterValueValidationIssue.ts@@ -0,0 +1,64 @@+import {+ type FieldMetadataType,+ type FilterableAndTSVectorFieldType,+ type ViewFilterOperand,+} from '@/types';+import { isRecordFilterValueValid } from '@/utils/filter/isRecordFilterValueValid';+import { convertViewFilterValueToString } from '@/utils/filter/utils/convertViewFilterValueToString';+import { getFilterTypeFromFieldType } from '@/utils/filter/utils/getFilterTypeFromFieldType';+import { FILTER_VALUE_FORMAT_HINTS } from '@/utils/filter/utils/validation-schemas/filterValueSchemasMap';+import { getFilterValueSchema } from '@/utils/filter/utils/validation-schemas/getFilterValueSchema';+import { isDefined } from '@/utils/validation/isDefined';++export type FilterValueValidationIssue = {+ stringifiedValue: string;+ operand: ViewFilterOperand;+ filterType: FilterableAndTSVectorFieldType;+ hint: string;+};++export const getFilterValueValidationIssue = ({+ fieldType,+ operand,+ subFieldName,+ value,+}: {+ fieldType: FieldMetadataType;+ operand: ViewFilterOperand;+ subFieldName?: string | null;+ value: unknown;+}): FilterValueValidationIssue | undefined => {+ const stringifiedValue = convertViewFilterValueToString(value);++ if (!isRecordFilterValueValid({ operand, value: stringifiedValue })) {+ return undefined;+ }++ const filterType = getFilterTypeFromFieldType(fieldType);++ const valueSchema = getFilterValueSchema({+ filterType,+ operand,+ subFieldName,+ });++ if (!isDefined(valueSchema)) {+ return undefined;+ }++ const parseResult = valueSchema.safeParse(stringifiedValue);++ if (parseResult.success) {+ return undefined;+ }++ return {+ stringifiedValue,+ operand,+ filterType,+ hint:+ FILTER_VALUE_FORMAT_HINTS[operand] ??+ parseResult.error.issues[0]?.message ??+ '',+ };+};diff --git a/packages/twenty-shared/src/utils/index.ts b/packages/twenty-shared/src/utils/index.tsindex be8a89e776b..c05c3ce4853 100644--- a/packages/twenty-shared/src/utils/index.ts+++ b/packages/twenty-shared/src/utils/index.ts@@ -156,7 +156,27 @@ export { isMatchingStringFilter } from './filter/utils/isMatchingStringFilter';export { isMatchingTSVectorFilter } from './filter/utils/isMatchingTSVectorFilter';export { isMatchingUUIDFilter } from './filter/utils/isMatchingUUIDFilter';export { arrayOfStringsOrVariablesSchema } from './filter/utils/validation-schemas/arrayOfStringsOrVariablesSchema';-export { arrayOfUuidOrVariableSchema } from './filter/utils/validation-schemas/arrayOfUuidsOrVariablesSchema';+export {+ strictArrayOfUuidOrVariableSchema,+ arrayOfUuidOrVariableSchema,+} from './filter/utils/validation-schemas/arrayOfUuidsOrVariablesSchema';+export {+ nonEmptyStringFilterValueSchema,+ numericFilterValueSchema,+ plainDateFilterValueSchema,+ instantFilterValueSchema,+ plainDateOrInstantFilterValueSchema,+ booleanFilterValueSchema,+ actorSourceFilterValueSchema,+} from './filter/utils/validation-schemas/filterValueScalarSchemas';+export {+ FILTER_VALUE_SCHEMAS_MAP,+ COMPOSITE_SUB_FIELD_VALUE_SCHEMAS,+ FILTER_VALUE_FORMAT_HINTS,+} from './filter/utils/validation-schemas/filterValueSchemasMap';+export { getFilterValueSchema } from './filter/utils/validation-schemas/getFilterValueSchema';+export type { FilterValueValidationIssue } from './filter/utils/validation-schemas/getFilterValueValidationIssue';+export { getFilterValueValidationIssue } from './filter/utils/validation-schemas/getFilterValueValidationIssue';export {relationFilterValueSchemaObject,jsonRelationFilterValueSchema,